Regex for replacing a single-quote with two single-quotes

前端 未结 8 1450
迷失自我
迷失自我 2020-12-16 09:24

I\'m running into an issue that I think is being caused by needing to double-up on some single quotes inside a string. However, JS\'s string.replace uses RegEx, and I\'ve ne

相关标签:
8条回答
  • 2020-12-16 09:37
    js> s = "abc'def'xyz"
    abc'def'xyz
    js> s.replace(/'/g, "''")
    abc''def''xyz
    
    0 讨论(0)
  • 2020-12-16 09:39

    JS's string.replace uses RegEx

    Not necessarily:

    var str = "O'Reilly's books";
    alert(str.replace("'", "''", 'g'));
    

    MDC's String replace reference:

    The pattern can be a string or a RegExp

    Mmm, my code above doesn't seem to work on IE6, so that will be:

    str.replace(/'/g, "''")
    

    like the others said, but using regexes for such simple operation is overkill.

    0 讨论(0)
  • 2020-12-16 09:39

    Try this:

    function QuoteEncoding(strvalue) {
        var strquotes = /(')/g;
        return "'" + strvalue.replace(strquotes, "''") + "'";
    }
    

    call this method as follows:

    QuoteEncoding(strvalue);
    
    0 讨论(0)
  • 2020-12-16 09:44

    Note that if you don't want to use RegExp (and there are often good reasons not to), the idiom for a simple string replacement is:

    str.split("'").join("''")
    

    Although the RegExp version is typically marginally faster, the string version can be a win when you don't know if there might be regex-special characters (like .) in the search string.

    0 讨论(0)
  • 2020-12-16 09:46

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

    Be sure to use the global match flag (g) so that you replace any and all occurrences in the string. More info here.

    0 讨论(0)
  • 2020-12-16 09:57

    Try this:

    yourstring = yourstring.replace(/'/g, "''")
    
    0 讨论(0)
提交回复
热议问题