javascript 用于转义逗号和双引号的javascript正则表达式
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8354494/
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
javascript regex for escaping comma and double quote
提问by Karan
I have to escape two special characters " and , in the string with the following rules.
我必须使用以下规则在字符串中转义两个特殊字符 " 和 , 。
Example:-
例子:-
- Mercu"ry should be converted into "Mercu""ry"
- Mercu,ry should be converted into "Mercu,ry"
- Mer"cu,ry should be converted into "Mer""cu,ry"
- Mercu"ry 应转换为 "Mercu""ry"
- Mercu,ry 应转换为“Mercu,ry”
- Mer"cu,ry 应转换为 "Mer""cu,ry"
Rules:-
规则:-
- Meaning comma or double quote should be escaped with double quote.
- Comma will escaped by wrapping the whole word in double quotes.
- If Double quote is found, then it double quote should be added at its position. Also the whole word should be wrapped inside the double quotes.
- 意思是逗号或双引号应该用双引号转义。
- 逗号将通过将整个单词括在双引号中来转义。
- 如果找到双引号,则应在其位置添加双引号。此外,整个单词应包含在双引号内。
Please suggest the regex pattern in javascript.
请建议 javascript 中的正则表达式模式。
回答by Seyeong Jeong
var test = [
'Mercu"ry', 'Mercu,ry', 'Mer"cu,ry', 'Mercury'
];
for (x in test) {
var s = test[x];
if (s.indexOf('"') != -1) {
s = s.replace(/"/g, '""');
}
if (s.match(/"|,/)) {
s = '"' + s + '"';
}
alert(s);
}
Test: http://jsfiddle.net/ZGFV5/
测试:http: //jsfiddle.net/ZGFV5/
Try to run the code with Mer""cury
:)
尝试使用Mer""cury
:)运行代码
回答by David Hu
Just always wrap the word in double quotes, and replace all double quotes with two:
只需将单词用双引号括起来,并将所有双引号替换为两个:
function escapeWord(word) {
return '"' + word.replace(/"/g, '""') + '"';
}
回答by Rory McCrossan
The regular expression to achieve this is /"/g
, so the following will work for your examples:
实现此目的的正则表达式是/"/g
,因此以下内容适用于您的示例:
var test1 = 'Mercu"ry'
var test2 = 'Mercu,ry'
var test3 = 'Mer"cu,ry'
var regex = /"/g;
var example1 = '"' + test1.replace(regex, '""') + '"';
var example2 = '"' + test2.replace(regex, '""') + '"';
var example3 = '"' + test3.replace(regex, '""') + '"';
alert(example1 + " : " + example2 + " : " + example3);