Replace multiple characters in one replace call

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

    Chaining is cool, why dismiss it?

    Anyway, here is another option in one replace:

    string.replace(/#|_/g,function(match) {return (match=="#")?"":" ";})
    

    The replace will choose "" if match=="#", " " if not.

    [Update] For a more generic solution, you could store your replacement strings in an object:

    var replaceChars={ "#":"" , "_":" " };
    string.replace(/#|_/g,function(match) {return replaceChars[match];})
    

提交回复
热议问题