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.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments