1

I am trying to write a JavaScript RegEx that properly adds escape characters to all the single and double quote characters in a string. For example, if I have the following string:

"Hey, how's it going? You're really good at this!"

The code should transform that string to:

"Hey, how\'s it going? You\'re really good at this!"

Below is my code:

var testString = "Hey, how's it going? You're really good at this!";
testString = testString.replace(/'/g, '\'').replace(/"/g, '\"');
alert(testString);

The quotes are currently not being replaced by an escape character.

Sebastian Simon
  • 18,263
  • 7
  • 55
  • 75
Henry Zhu
  • 2,488
  • 9
  • 43
  • 87

1 Answers1

1

The problem is that your

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

replacement strings still only have a single character in them:

const str1 = '\'';
const str2 = '\"';
console.log(str1, str2);
console.log(str1.length, str2.length);
\'

and

\"

in a string literal only indicate unnecessarily escaped characters: \' is not an escape sequence (like \n), so it's equivalent to '.

Put another backslash next to the backslash to indicate a literal backslash:

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

You can also use String.raw to avoid having to type the backslashes twice, but it's not worth it for something this short:

testString.replace(/'/g, String.raw`\'`).replace(/"/g, String.raw`\"`);
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320