Replace multiple characters in one replace call

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

    Here is a "safe HTML" function using a 'reduce' multiple replacement function (this function applies each replacement to the entire string, so dependencies among replacements are significant).

    // Test:
    document.write(SafeHTML('
    \n\ x
    ')); function SafeHTML(str) { const replacements = [ {'&':'&'}, {'<':'<'}, {'>':'>'}, {'"':'"'}, {"'":'''}, {'`':'`'}, {'\n':'
    '}, {' ':' '} ]; return replaceManyStr(replacements,str); } // HTMLToSafeHTML function replaceManyStr(replacements,str) { return replacements.reduce((accum,t) => accum.replace(new RegExp(Object.keys(t)[0],'g'),t[Object.keys(t)[0]]),str); }

提交回复
热议问题