[英]How to escape single quote within another string which contains single quote in javascript?
Hi I want to escape single quote within another string. 嗨,我想在另一个字符串中转义单引号。
I have the following string: 我有以下字符串:
'I'm a javascript programmer'
In the above string , I need to escape single quote 在上面的字符串中,我需要转义单引号
and the expected output is: 预期的输出是:
'I\'m a javascript programmer'
I required this to handle in eval() in javascript. 我需要在JavaScript中的eval()中进行处理。
The String would be like this... 字符串会像这样...
"[['string's one','string two','string's three']]"
How to solve this. 如何解决这个问题。 Thanks in advance...
提前致谢...
var s = "my string's"
s = s.replace(/'/g, "\\'");
The proper way to escape quotes in an html string would be with a character entity. 转义html字符串中引号的正确方法是使用字符实体。
'I'm a javascript programmer'
The same goes for double quotes: 双引号也是如此:
'"I'm a javascript programmer"'
You can try lookahead assertions to achieve the desired effect: 您可以尝试先行断言以获得所需的效果:
var str = "'I'm a javascript's programmer'";
str = str.replace(/(?!^)'(?!$)/g, "\\'");
( Fiddle ). ( 小提琴 )。 Unlike Shimon's answer, this can also deal with double single quotes (
''
). 与西蒙的回答,这也可以对付双单引号(
''
)。
Negative lookahead assertion (?! )
doesn't do any matching by itself but it ensures that the asserted expression doesn't occur at the given position (ie start of string ^
doesn't occur before the quote and end of string $
doesn't occur after the quote). 否定的超前断言
(?! )
本身不会进行任何匹配,但可以确保断言的表达式不会在给定的位置发生(即,字符串^
开始不会在引号和字符串$
结束之前出现)在引号后出现)。
This can do the trick: 这可以解决问题:
var str = "'I'm a js programer.'";
str.replace(/(\w)'(\w)/g, "$1\\\'$2");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.