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.
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.
'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");
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.