小编典典

在一个替换呼叫中替换多个字符

javascript

一个非常简单的小问题,但是我不太明白该怎么做。

我需要将’_’的每个实例替换为空格,并将’#’的每个实例替换为空/空。

var string = '#Please send_an_information_pack_to_the_following_address:';

我已经试过了:

string.replace('#','').replace('_', ' ');

我真的不喜欢这样的链接命令。还有另一种方法可以做到这一点吗?


阅读 325

收藏
2020-05-01

共1个答案

小编典典

使用OR运算符(|):

var str = '#this #is__ __#a test###__';
str.replace(/#|_/g,''); // result: "this is a test"

您还可以使用字符类:

str.replace(/[#_]/g,'');

Fiddle

如果您想用一件事替换哈希值,而用另一件事替换下划线,则只需要链接即可。但是,您可以添加一个原型:

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';

但是为什么不连锁呢?我认为这没有错。

2020-05-01