我编写了下面的函数来用连字符或反向转换空格
- 带连字符的空格
str.trim().replace(/\s+/g, '-')
- 带空格的连字符
str.replace(/\-/g,' ')
但现在我尝试用双连字符替换单连字符,我无法使用点 1 函数,因为它转换单个/多个出现而不是单个。
有没有办法编写在单个公式中执行 3 个操作的正则表达式
- 将正斜杠转换为下划线
replace(/\//g, '_')
- 用单个连字符转换空格
- 将单个连字符转换为多个连字符
例如 正则表达式 1 处更改
"Name/Er-Gourav Mukhija" into "Name_Er--Gourav-Mukhija"
正则表达式 2 做相反的事情。
最佳答案
您可以使用回调函数而不是替换字符串。这样您就可以一次指定和替换所有字符。
const input = 'Name/Er-Gourav Mukhija';
const translate = {
'/': '_',
'-': '--',
' ': '-',
};
const reverse = {
'_': '/',
'--': '-',
'-': ' ',
};
// This is just a helper function that takes
// the input string, the regex and the object
// to translate snippets.
function replaceWithObject( input, regex, translationObj ) {
return input.replace( regex, function( match ) {
return translationObj[ match ] ? translationObj[ match ] : match;
} );
}
function convertString( input ) {
// Search for /, - and spaces
return replaceWithObject( input, /(\/|\-|\s)/g, translate );
}
function reverseConvertedString( input ) {
// Search for _, -- and - (the order here is very important!)
return replaceWithObject( input, /(_|\-\-|\-)/g, reverse );
}
const result = convertString( input );
console.log( result );
console.log( reverseConvertedString( result ) );
关于javascript - 正则表达式替换单个或多个连字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46694660/