如何在 Javascript 中为字符串添加斜杠?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2195568/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I add slashes to a string in Javascript?
提问by TIMEX
Just a string. Add \' to it every time there is a single quote.
只是一个字符串。每次有单引号时都添加 \' 。
回答by Kobi
replaceworks for the first quote, so you need a tiny regular expression:
replace适用于第一个引号,因此您需要一个很小的正则表达式:
str = str.replace(/'/g, "\'");
回答by Somnath Muluk
Following JavaScript function handles ', ", \b, \t, \n, \f or \r equivalent of php function addslashes().
下面的 JavaScript 函数处理 '、"、\b、\t、\n、\f 或 \r 等价于 php 函数 addlashes()。
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, '\"');
}
回答by filip
A string can be escaped comprehensively and compactly using JSON.stringify. It is part of JavaScript as of ECMAScript 5and supported by major newer browser versions.
可以使用 JSON.stringify 全面紧凑地转义字符串。从ECMAScript 5 开始,它是 JavaScript 的一部分,并受到主要的新浏览器版本的支持。
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 \rand \nare escaped properly in a relatively compact statement.
使用这种方法,还可以将特殊字符作为空字节、unicode 字符和换行符,\r并\n在相对紧凑的语句中正确转义。
回答by Mic
To be sure, you need to not only replace the single quotes, but as well the already escaped ones:
可以肯定的是,您不仅需要替换单引号,还需要替换已经转义的单引号:
"first ' and \' second".replace(/'|\'/g, "\'")
回答by lance
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.
如果您在准备将字符串发送到 alert() 或其他任何单引号字符可能会绊倒您的地方进行替换,那么您没有要求的答案可能会有所帮助。
str.replace("'",'\x27')
That will replace all single quotes with the hex codefor single quote.
这将用单引号的十六进制代码替换所有单引号。
回答by womp
var myNewString = myOldString.replace(/'/g, "\'");
回答by Vivin Paliath
var str = "This is a single quote: ' and so is this: '";
console.log(str);
var replaced = str.replace(/'/g, "\'");
console.log(replaced);
Gives you:
给你:
This is a single quote: ' and so is this: '
This is a single quote: \' and so is this: \'
回答by Shahadat Hossain Khan
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, '<')
.replace(/>/g, '>').replace(/\u0000/g, '\0');
}
}
Usage: alert(str.addSlashes());
用法:警报(str.addSlashes());

