How do I add slashes to a string in Javascript?

后端 未结 8 1721
陌清茗
陌清茗 2020-12-29 19:05

Just a string. Add \\\' to it every time there is a single quote.

相关标签:
8条回答
  • 2020-12-29 19:30
    var myNewString = myOldString.replace(/'/g, "\\'");
    
    0 讨论(0)
  • 2020-12-29 19:31

    Following JavaScript function handles ', ", \b, \t, \n, \f or \r equivalent of php function addslashes().

    function addslashes(string) {
        return string.replace(/\\/g, '\\\\').
            replace(/\u0008/g, '\\b').
            replace(/\t/g, '\\t').
            replace(/\n/g, '\\n').
            replace(/\f/g, '\\f').
            replace(/\r/g, '\\r').
            replace(/'/g, '\\\'').
            replace(/"/g, '\\"');
    }
    
    0 讨论(0)
  • 2020-12-29 19:31
    if (!String.prototype.hasOwnProperty('addSlashes')) {
        String.prototype.addSlashes = function() {
            return this.replace(/&/g, '&') /* This MUST be the 1st replacement. */
                 .replace(/'/g, ''') /* The 4 other predefined entities, required. */
                 .replace(/"/g, '"')
                 .replace(/\\/g, '\\\\')
                 .replace(/</g, '&lt;')
                 .replace(/>/g, '&gt;').replace(/\u0000/g, '\\0');
            }
    }
    

    Usage: alert(str.addSlashes());

    ref: https://stackoverflow.com/a/9756789/3584667

    0 讨论(0)
  • 2020-12-29 19:38

    A string can be escaped comprehensively and compactly using JSON.stringify. It is part of JavaScript as of ECMAScript 5 and supported by major newer browser versions.

    str = JSON.stringify(String(str));
    str = str.substring(1, str.length-1);
    

    Using this approach, also special chars as the null byte, unicode characters and line breaks \r and \n are escaped properly in a relatively compact statement.

    0 讨论(0)
  • 2020-12-29 19:43

    To be sure, you need to not only replace the single quotes, but as well the already escaped ones:

    "first ' and \' second".replace(/'|\\'/g, "\\'")
    
    0 讨论(0)
  • 2020-12-29 19:43

    An answer you didn't ask for that may be helpful, if you're doing the replacement in preparation for sending the string into alert() -- or anything else where a single quote character might trip you up.

    str.replace("'",'\x27')
    

    That will replace all single quotes with the hex code for single quote.

    0 讨论(0)
提交回复
热议问题