简体   繁体   中英

Escaping double quotes in JavaScript from a string in a variable

I have these two scenarios:


console.log(('hello "friend" what\'s up?').replace(/\"/g, '\\"'));

I receive the expected result:

hello "friend" what's up?


But , if I do this:

var val = 'hello "friend" what\'s up?';
val.replace(/\"/g, '\\"');
console.log(val);

I get...

hello "friend" what's up?

(the result needs to be hello \\"friend\\" what's up? )


The only difference is that the second one uses an already created variable that contains the string. Why doesn't the second scenario actually replace the double quotes with \\" ?

From the MDN documentation :

The replace() method returns a new string with some or all matches of a pattern replaced by a replacement.

You need to do val = val.replace(/\\"/g, '\\\\"'); so that you're assigning the new string returned by calling replace to your variable.

Actually by doing

val.replace(/\"/g, '\\"');

You're not assigning the replaced value back to val . For that you will need:

val = val.replace(/\"/g, '\\"');
val.replace(/\"/g, '\\"');

In the above code you are not reassigning to val ;

Try this to get the expected result.

val = val.replace(/\"/g, '\\"');

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