Ste*_*son 62 javascript string quotes escaping backslash
JavaScript是否有像PHP addslashes(或addcslashes)函数这样的内置函数来向需要在字符串中转义的字符添加反斜杠?
例如,这个:
这是一个带有"单引号"和"双引号"的演示字符串.
...会成为:
这是一个带有"单引号"和"双引号"的演示字符串.
Pao*_*ino 89
http://locutus.io/php/strings/addslashes/
function addslashes( str ) {
return (str + '').replace(/[\\"']/g, '\\$&').replace(/\u0000/g, '\\0');
}
Run Code Online (Sandbox Code Playgroud)
小智 71
您也可以尝试使用双引号:
JSON.stringify(sDemoString).slice(1, -1);
JSON.stringify('my string with "quotes"').slice(1, -1);
Run Code Online (Sandbox Code Playgroud)
Mar*_*aio 40
Paolo Bergantino提供的函数的变体,直接在String上工作:
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');
}
Run Code Online (Sandbox Code Playgroud)
通过在库中添加上面的代码,您将能够:
var test = "hello single ' double \" and slash \\ yippie";
alert(test.addSlashes());
Run Code Online (Sandbox Code Playgroud)
编辑:
根据评论中的建议,无论谁关注JavaScript库之间的冲突,都可以添加以下代码:
if(!String.prototype.addSlashes)
{
String.prototype.addSlashes = function()...
}
else
alert("Warning: String.addSlashes has already been declared elsewhere.");
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
115138 次 |
| 最近记录: |