Javascript replace “ ' ” with “ '' ”

后端 未结 7 675
陌清茗
陌清茗 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:37

    The problem is that

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

    will only replace the first instance of '. To fix this, do the following instead

    temp.replace(/'/g, "''"));
    

    This will ensure it goes though and replaces all instances of the single quote instead of just the first.

    0 讨论(0)
  • 2021-01-22 12:37

    The trick is quoting each string with the other quote character:

    temp.replace(/'/g, '"');
    

    Edit: Ben Lee is correct about the regex, updated above. However, I still gather it that you want to replace with " (one double quote), not '' (two single quotes).

    0 讨论(0)
  • 2021-01-22 12:37

    Have you simply tried this?

    temp.replace("'", "''");
    
    0 讨论(0)
  • 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
    
    0 讨论(0)
  • 2021-01-22 12:47

    So it's basically changing the single quote character with 2 single quote characters, right? If that's the case you might wanna use the global flag, g at the end of yoir Regular Expression and assing it back to your value (temp)

    temp = temp.replace(/'/g,"''");
    
    0 讨论(0)
  • 2021-01-22 12:54
    while (str.indexOf("'") >= 0)
        {
            var newStr = str.replace("'", "\"");
            str = newStr;
        }
    
    0 讨论(0)
提交回复
热议问题