我需要将'_'的每个实例替换为一个空格,并将'#'的每个实例替换为无/空。
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('_', ' ');
我真的不喜欢这样的链接命令。有没有另一种方法可以一次性完成?
当前回答
捆绑很酷,为什么要抛弃它呢?
不管怎样,这里有一个替换的另一个选项:
string.replace(/#|_/g,function(match) {return (match=="#")?"":" ";})
如果匹配==“#”,则替换将选择“”,如果不匹配则选择“”。
对于一个更通用的解决方案,你可以将替换字符串存储在一个对象中:
var replaceChars={ "#":"" , "_":" " };
string.replace(/#|_/g,function(match) {return replaceChars[match];})
其他回答
不知道为什么还没有人提供这个解决方案,但我发现它非常有效:
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])
}
}
你可以添加任何你喜欢的占位符,而不必更新你的函数。简单!
还可以将RegExp对象传递给replace方法,如
var regexUnderscore = new RegExp("_", "g"); //indicates global match
var regexHash = new RegExp("#", "g");
string.replace(regexHash, "").replace(regexUnderscore, " ");
Javascript RegExp
对于什么都不替换,tckmn的答案是最好的。
如果你需要替换对应匹配的特定字符串,下面是Voicu和Christophe回答的一个变体,避免重复被匹配的内容,这样你就不必记得在两个地方添加新的匹配:
const replacements = {
'’': "'",
'“': '"',
'”': '"',
'—': '---',
'–': '--',
};
const replacement_regex = new RegExp(Object
.keys(replacements)
// escape any regex literals found in the replacement keys:
.map(e => e.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'))
.join('|')
, 'g');
return text.replace(replacement_regex, e => replacements[e]);
如果只是使用if else语句的简写呢?使它成为一行程序。
const betterWriting = string.replace(/[#_]/gi , d => d === '#' ? '' : ' ' );
使用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” );
为什么不加链子呢?我看不出这有什么不对。