I have a string like this
This is\' it
I would like it to look like this
This is' it
Nothing I do seems to work
> "This is\' it".replace(/\\'/,"'");
'This is\' it'
> "This is\' it".replace("'",/\\'/);
'This is/\\\\\'/ it'
> "This is\' it".replace("\'","'");
'This is\' it'
> "This is\' it".replace("'","\'");
'This is\' it'
UPDATE: This is a little hard to wrap my head around but I had my example string inside an array something like.
> ["hello world's"]
[ 'hello world\'s' ]
It automatically happens like so:
> var a = ["hello world's"]
undefined
> a
[ 'hello world\'s' ]
> a[0]
'hello world\'s'
> console.log(a[0])
hello world's
undefined
> console.log(a)
[ 'hello world\'s' ]
undefined
>
I have a string like this
This is\' it
I would like it to look like this
This is' it
Nothing I do seems to work
> "This is\' it".replace(/\\'/,"'");
'This is\' it'
> "This is\' it".replace("'",/\\'/);
'This is/\\\\\'/ it'
> "This is\' it".replace("\'","'");
'This is\' it'
> "This is\' it".replace("'","\'");
'This is\' it'
UPDATE: This is a little hard to wrap my head around but I had my example string inside an array something like.
> ["hello world's"]
[ 'hello world\'s' ]
It automatically happens like so:
> var a = ["hello world's"]
undefined
> a
[ 'hello world\'s' ]
> a[0]
'hello world\'s'
> console.log(a[0])
hello world's
undefined
> console.log(a)
[ 'hello world\'s' ]
undefined
>
Share
Improve this question
edited Sep 5, 2012 at 22:34
ThomasReggi
asked Sep 5, 2012 at 22:19
ThomasReggiThomasReggi
59.6k97 gold badges258 silver badges459 bronze badges
1
-
6
console.log("This is\' it")
returnsThis is' it
for me. – Blender Commented Sep 5, 2012 at 22:21
3 Answers
Reset to default 7None of your test strings actually contain backslashes. The string you are inputting each time is: This is' it
because the backslash escapes the single quote.
Your first (regex-based) solution is almost perfect, just missing the global modifier /\\'/g
to replace all matches, not just the first. To see this in action, try the following:
> "This is\\' it"
"This is\' it"
> "This is\\' it".replace(/\\'/g,"'");
"This is' it"
Give this a shot:
"This is\' it".replace(/\\(.?)/g, function (s, n1) {
switch (n1) {
case '\\':
return '\\';
case '0':
return '\u0000';
case '':
return '';
default:
return n1;
});
Taken from http://phpjs/functions/stripslashes:537
I think the first option in your question works. When you mention it as a string in JavaScript, you need to escape the \
so that it is read as a string rather than a special character.
Check this jsFiddle : http://jsfiddle/T7Du4/2/
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1742306702a4419082.html
评论列表(0条)