Replace multiple characters in one replace call

前端 未结 15 2516
失恋的感觉
失恋的感觉 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:54

    If you want to replace multiple characters you can call the String.prototype.replace() with the replacement argument being a function that gets called for each match. All you need is an object representing the character mapping which you will use in that function.

    For example, if you want a replaced with x, b with y and c with z, you can do something like this:

    var chars = {'a':'x','b':'y','c':'z'};
    var s = '234abc567bbbbac';
    s = s.replace(/[abc]/g, m => chars[m]);
    console.log(s);
    

    Output: 234xyz567yyyyxz

提交回复
热议问题