Javascript replace “ ' ” with “ '' ”

后端 未结 7 679
陌清茗
陌清茗 2021-01-22 12:24

I\'m trying to replace the \"\'\" character with the \"\'\'\" string using the replace method, like this:

temp.replace(\"\\\'\", \"\'\'\");

but

7条回答
  •  故里飘歌
    2021-01-22 12:42

    You're actually trying to replace (\'), not just the single quote character. There is no need to escape a single quote in a string delimited by double quotes, because they don't signify the end of a string...

    Replace will only replace the first quote matched, unless you're using our old friend Regexp. The downside being Regular Expressions tend to be slow. I haven't checked to see which is faster, but you could try using split:

    var chunks = temp.split("'").join("''");
    
    test = "string cont'aining single 'quotes".split("'").join("''");//in firebug console
    //returns "string cont''aining single ''quotes" as expected
    

提交回复
热议问题