代码之家  ›  专栏  ›  技术社区  ›  Steve Harrison

JavaScript中的转义字符串

  •  56
  • Steve Harrison  · 技术社区  · 17 年前

    JavaScript是否有像PHP一样的内置函数 addslashes addcslashes )函数向字符串中需要转义的字符添加反斜杠?

    例如,这:

    这是一个带有 “单引号”和“双引号”。

    …将成为:

    这是一个带有 \“单引号”和 \“双引号\”。

    4 回复  |  直到 14 年前
        1
  •  94
  •   Raman Sahasi    9 年前

    http://locutus.io/php/strings/addslashes/

    function addslashes( str ) {
        return (str + '').replace(/[\\"']/g, '\\$&').replace(/\u0000/g, '\\0');
    }
    
        2
  •  85
  •   Knu    11 年前

    您也可以尝试使用双引号:

    JSON.stringify(sDemoString).slice(1, -1);
    JSON.stringify('my string with "quotes"').slice(1, -1);
    
        3
  •  40
  •   SharpC Paul    9 年前

    函数的一种变体,由 保罗·贝甘蒂诺 直接作用于字符串的:

    String.prototype.addSlashes = function() 
    { 
       //no need to do (str+'') anymore because 'this' can only be a string
       return this.replace(/[\\"']/g, '\\$&').replace(/\u0000/g, '\\0');
    } 
    

    var test = "hello single ' double \" and slash \\ yippie";
    alert(test.addSlashes());
    

    编辑:

    if(!String.prototype.addSlashes)
    {
       String.prototype.addSlashes = function()... 
    }
    else
       alert("Warning: String.addSlashes has already been declared elsewhere.");
    
        4
  •  3
  •   tcmoore    9 年前

    使用encodeURI()

    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURI

    转义字符串中几乎所有有问题的字符,以便在web应用程序中使用正确的JSON编码和传输。这不是一个完美的验证解决方案,但它抓住了低垂的果实。

        5
  •  0
  •   Renish Gotecha    5 年前

    你也可以用这个

    let str = "hello single ' double \" and slash \\ yippie";
    
    let escapeStr = escape(str);
    document.write("<b>str : </b>"+str);
    document.write("<br/><b>escapeStr : </b>"+escapeStr);
    document.write("<br/><b>unEscapeStr : </b> "+unescape(escapeStr));