在一次替换调用中替换多个字符 [英] 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 = '#请发送_an_information_pack_to_the_following_address:';
我已经试过了:
string.replace('#','').replace('_',' ');
我真的不喜欢像这样链接命令.有没有另一种方法可以做到这一点?
I don't really like chaining commands like this. Is there another way to do it in one?
推荐答案
使用 OR 运算符 (|
):
Use the OR operator (|
):
var str = '#this #is__ __#a test###__';
str.replace(/#|_/g,''); // result: "this is a test"
你也可以使用字符类:
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屋!