Replace multiple characters in one replace call

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

    You could also try this :

    function replaceStr(str, find, replace) {
        for (var i = 0; i < find.length; i++) {
            str = str.replace(new RegExp(find[i], 'gi'), replace[i]);
        }
        return str;
    }
    
    var text = "#here_is_the_one#";
    var find = ["#","_"];
    var replace = ['',' '];
    text = replaceStr(text, find, replace);
    console.log(text);
    

    find refers to the text to be found and replace to the text to be replaced with

    This will be replacing case insensitive characters. To do otherway just change the Regex flags as required. Eg: for case sensitive replace :

    new RegExp(find[i], 'g')
    

提交回复
热议问题