Reputation: 59365
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
>
Upvotes: 2
Views: 4645
Reputation: 1492
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.net/T7Du4/2/
Upvotes: 0
Reputation: 324640
None 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"
Upvotes: 7
Reputation: 191749
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.org/functions/stripslashes:537
Upvotes: 0