Replace multiple characters in one replace call

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

    Here is another version using String Prototype. Enjoy!

    String.prototype.replaceAll = function(obj) {
        let finalString = '';
        let word = this;
        for (let each of word){
            for (const o in obj){
                const value = obj[o];
                if (each == o){
                    each = value;
                }
            }
            finalString += each;
        }
    
        return finalString;
    };
    
    'abc'.replaceAll({'a':'x', 'b':'y'}); //"xyc"
    
    0 讨论(0)
  • 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

    0 讨论(0)
  • 2020-11-22 17:54

    You can just try this :

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

    this will replace .,- and # with your replacechar !

    0 讨论(0)
提交回复
热议问题