Replace multiple characters in one replace call

前端 未结 15 2559
失恋的感觉
失恋的感觉 2020-11-22 17:24

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 no

15条回答
  •  感动是毒
    2020-11-22 17:27

    Use the OR operator (|):

    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.

提交回复
热议问题