Regex inconsistent

function telephoneCheck(str) {
  var paro = new RegExp('\\x28','g');
  var pare = new RegExp('\\x29','g');
  var dash = new RegExp('\\x2D','g');
  var clen;
  clen = str.replace(paro,"");
  clen = str.replace(pare,"");
  clen = str.replace(dash,"");
  console.log(clen);
  return true;
}

It removes all dashes but not the parenthesis. I don’t understand why the one works while the other two don’t… I’ve use similar regexes in other challenges and I didn’t face a problem…

Edit: I initialized clen as str and used replace on clen. Now I get the expected result. My new question is: why does it work now and not before?

The code that didn’t work is the one I’m providing. The one that did is described in the edit.

See my comments below for what happens at each step of the following code.

function telephoneCheck(str) {
  var paro = new RegExp('\\x28','g');
  var pare = new RegExp('\\x29','g');
  var dash = new RegExp('\\x2D','g');
  var clen;
  clen = str.replace(paro,""); // clen now is '555)555-5555'
  clen = str.replace(pare,""); // clen now is '(555555-5555'
  clen = str.replace(dash,""); // clen now is '(555)5555555'
  console.log(clen);
  return true;
}

telephoneCheck('(555)555-5555')

You are assigning the value the returned value of the replace on str to clen each time overwriting what clen is. str is never affected, because the replace does not mutate the original string, but instead returns a new string. You need to substitute clen for str for the 2nd and 3rd replace statements to work as you want.

1 Like