使用JavaScript替换未跟随相同字符的字符。
我有一个字符串,其中字符串可能包含正斜杠(/)。如果字符串包含一个正斜杠,那么我需要用两个'/'替换它,以便它被转义。
例如'sample/word'
需要成为'sample//word'
另一个规则是奇数个斜杠需要成为偶数。
例如'///'
=> '////'
我已经研究过使用正则表达式,但据我所知,JavaScript ES6中没有所需的负面外观。任何帮助赞赏!
我一直在使用的示例字符串:
let strs = [
'sample/single',
'sample//double',
'sample',
'//',
'/',
'//sample',
'sample//',
'/sample',
'sample/',
'sample///',
'///sample',
'////sample',
'/////sample',
'sample/////',
'sample////',
'sample / again',
'sa/mple agai/n'
]
试试这个:
let strs = [
'sample/single',
'sample//double',
'sample',
'//',
'/',
'//sample',
'sample//',
'/sample',
'sample/',
'sample///',
'///sample',
'////sample',
'/////sample',
'sample/////',
'sample////',
'sample / again',
'sa/mple agai/n'
];
const slashMeUpBro = (word) => {
let words = word.split('//');
word.split('//').forEach((word, index) => words[index] = word.replace(/\/+/g, '//'));
return words.join('//');
}
strs.forEach(word => console.log(slashMeUpBro(word)));
使用上面的规则,您可以使用以下函数来满足它们并实现输出。在这里,我将函数传递给replace
函数,它允许您检查正则表达式是否匹配奇数或偶数量的/
,从而相应地替换:
let strs = [
'sample/single',
'sample//double',
'sample',
'//',
'/',
'//sample',
'sample//',
'/sample',
'sample/',
'sample///',
'///sample',
'////sample',
'/////sample',
'sample/////',
'sample////',
'sample / again',
'sa/mple agai/n'
];
let result =
strs.map(elem => elem.replace(/\/+/g, match => match.length % 2 != 0 ? match+'/':match));
console.log(result);
这仅适用于行中的/字符作为其计算总数/文本,适用于除最后一个之外的数据集,这在某种程度上可能对您有所帮助。
var newstr = str;
if( str.match(/([/])/g).length % 2 == 1 )
newstr = str.replace(/([/])/g, "$1$1");
如果你想使用正则表达式,你可以使用:
(^|[^\/])(\/)(?=(?:\/\/)*(?!\/))
说明
(^|[^\/])
第一个捕获组来断言该行的开头或匹配而不是正斜杠(\/)
第二个捕获组匹配正斜杠(?=
积极前瞻
(?:\/\/)*
重复零次或多次//
(?!\/)
否定前瞻以断言下面的内容不是正斜杠)
关闭积极向前看替换为2个捕获组,然后是正斜杠
$1$2/
let pattern = /(^|[^\/])(\/)(?=(?:\/\/)*(?!\/))/g;
let strs = [
'//\n/',
'sample/single',
'sample//double',
'sample',
'//',
'/',
'//sample',
'sample//',
'/sample',
'sample/',
'sample///',
'///sample',
'////sample',
'/////sample',
'sample/////',
'sample////',
'sample / again',
'sa/mple agai/n'
];
strs.forEach((s) => {
console.log(s.replace(pattern, "$1$2/"))
});