在一个替换呼叫中替换多个字符 [英] Replace multiple characters in one replace call
问题描述
非常简单的小问题,但我不太明白该怎么做。
Very simple little question, but I don't quite understand how to do it.
我需要用空格替换'_'的每个实例,并且每个'#'实例都没有/空。
I need to replace every instance of '_' with a space, and every instance of '#' with nothing/empty.
var string ='#Please send_an_information_pack_to_the_following_address:';
我试过这个:
string.replace('#','')。replace('_','' );
我并没有真正链接这样的命令,但还有其他方法可以在一个方法中完成吗?
I don't really chaining commands like this, but is there another way to do it in one?
推荐答案
使用OR运算符( |
):
var str = '#this #is__ __#a test###__';
str.replace(/#|_/g,''); // result: "this is a test"
你也可以使用一个字符类:
You could also use a character class:
str.replace(/[#_]/g,'');
小提琴
如果你想用一个东西替换散列而用另一个东西替换下划线,那么你只需要链接。但是,您可以添加原型:
Fiddle
If you want to replace the hash with one thing and the underscore with another, then you will just have to chain. However, you could add a prototype:
String.prototype.allReplace = function(obj) {
var retStr = this;
for (var x in obj) {
retStr = retStr.replace(new RegExp(x, 'g'), obj[x]);
}
return retStr;
};
console.log('aabbaabbcc'.allReplace({'a': 'h', 'b': 'o'}));
// console.log 'hhoohhoocc';
为什么不连锁?我认为没错。
Why not chain, though? I see nothing wrong with that.
这篇关于在一个替换呼叫中替换多个字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!