1

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 \"?

1

3 Answers 3

3

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.

Sign up to request clarification or add additional context in comments.

2 Comments

I feel stupid. Had my "jQuery" mode on, as in $(this).attr('something', 'value'); Thank you!
Is it necessary to use regular expressions for simple substitutions of literal strings?
1

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, '\\"');

Comments

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

In the above code you are not reassigning to val;

Try this to get the expected result.

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.