我需要将'_'的每个实例替换为一个空格,并将'#'的每个实例替换为无/空。
var string = '#Please send_an_information_pack_to_the_following_address:';
我试过了:
string.replace('#','').replace('_', ' ');
我真的不喜欢这样的链接命令。有没有另一种方法可以一次性完成?
我需要将'_'的每个实例替换为一个空格,并将'#'的每个实例替换为无/空。
var string = '#Please send_an_information_pack_to_the_following_address:';
我试过了:
string.replace('#','').replace('_', ' ');
我真的不喜欢这样的链接命令。有没有另一种方法可以一次性完成?
当前回答
使用OR运算符(|):
Var STR = '#this #is__ __#a test###__'; console.log ( Str.replace (/#|_/g, ") // "this is a test" )
你也可以使用字符类:
str.replace(/[#_]/g,'');
小提琴
如果你想用一个东西替换散列,用另一个东西替换下划线,那么你只需要链
函数allReplace(str, obj) { For (const x in obj) { str = str.replace(new RegExp(x, 'g'), obj[x]); } 返回str; }; console.log ( allReplace (abcd-abcd, {' a ': ' h ', ' b ': ' o ' } ) // ' hocd-hocd” );
为什么不加链子呢?我看不出这有什么不对。
其他回答
使用OR运算符(|):
Var STR = '#this #is__ __#a test###__'; console.log ( Str.replace (/#|_/g, ") // "this is a test" )
你也可以使用字符类:
str.replace(/[#_]/g,'');
小提琴
如果你想用一个东西替换散列,用另一个东西替换下划线,那么你只需要链
函数allReplace(str, obj) { For (const x in obj) { str = str.replace(new RegExp(x, 'g'), obj[x]); } 返回str; }; console.log ( allReplace (abcd-abcd, {' a ': ' h ', ' b ': ' o ' } ) // ' hocd-hocd” );
为什么不加链子呢?我看不出这有什么不对。
在正则表达式上指定/g (global)标志来替换所有匹配项,而不仅仅是第一个:
string.replace(/_/g, ' ').replace(/#/g, '')
要用一种东西替换一个字符,用另一种东西替换另一个字符,你真的不能避免需要两个单独的调用来替换。你可以把它抽象成一个函数,就像门把手做的那样,尽管我可能会让它把一个对象的旧/新作为键/值对,而不是一个平面数组。
你也可以试试这个:
function replaceStr(str, find, replace) {
for (var i = 0; i < find.length; i++) {
str = str.replace(new RegExp(find[i], 'gi'), replace[i]);
}
return str;
}
var text = "#here_is_the_one#";
var find = ["#","_"];
var replace = ['',' '];
text = replaceStr(text, find, replace);
console.log(text);
Find指要查找的文本,replace指要替换的文本
这将取代不区分大小写的字符。否则,只需根据需要更改Regex标志。对于区分大小写的替换:
new RegExp(find[i], 'g')
你可以试试这个:
str.replace(/[.#]/g, 'replacechar');
这将用你的replacechar !
不知道为什么还没有人提供这个解决方案,但我发现它非常有效:
var string = '#Please send_an_information_pack_to_the_following_address:'
var placeholders = [
"_": " ",
"#": ""
]
for(var placeholder in placeholders){
while(string.indexOf(placeholder) > -1) {
string = string.replace(placeholder, placeholders[placeholder])
}
}
你可以添加任何你喜欢的占位符,而不必更新你的函数。简单!