简体   繁体   中英

Remove single quote character escaping

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
> 

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"

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

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/

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM