Zac Collier Zac Collier - 5 months ago 23
Javascript Question

Escaping Regex single-quote creates extra backslashes on

I am trying to write a prototype method that first needs to escape backslashes

when the input contains a plain single quote
. (I am aware that extending the prototype is bad practice in almost any other circumstance - this is merely a practice problem I'm trying to solve.)

I've checked out the Regex wiki and tried implementing the solutions to several regex-related questions, but I still seem to be missing something. In all of my attempts, I've been unable to 'escape the escape' as shown below:

String.prototype.escapeQuote = function () {
const regex = /\'/g;
const str = `${this}`;
const subst = `\\'`;
const result = str.replace(regex, subst);
return result;

var str = "this method doesn't work...";

When I run this code, I expect the output to be:

this method doesn\'t work...

But the output I get when I run it on is:

'this method doesn\\\'t work...'

or just
doesn't work either (perhaps it goes without saying) - either way the result is:

'this method doesn\'t work...'

I am pretty fuzzy on Regex, but trying to improve, so I'd appreciate any help you could provide - and, for that matter, any relevant answers I might have missed.


That's a rendering artifact of how the REPL you are using represents a string when it displays a string as the result of evaluating your code.

Note that it also wraps it in ' to indicate it is a string.

There are no slashes in the string itself, which you can see in this example:

String.prototype.escapeQuote = function() {
  const regex = /(')/g;
  const subst = `\\'`;
  const result = this.replace(regex, subst);
  return result;

const str = `doesn't this sound awesome`;
alert(str + "\n\n" + str.escapeQuote());