-1

I am trying to use the regex function of JavaScript to replace my string with desired value.But the regex keeps failing when the string has this format '(content)'

Here's my code for Regex:

     changeFormat = function (oldValue, newValue) {
      var changeData = "http://www.semanticweb.ontology-91#rabindranath_tagore_(film)";
      var regex = new RegExp(oldValue, 'g');
      console.log(regex);
      var source = changeData.replace(regex, newValue);
      console.log(source);
    };
    
    
changeFormat("http://www.semanticweb.ontology-91#rabindranath_tagore_(film)","rabindranath_tagore_(film)");

I got my output as "http://www.semanticweb.ontology-91#rabindranath_tagore_(film)" instead of "rabindranath_tagore_(film)"

The above behavior is because of the brackets "()".

1 Answers1

0

I think you need to escape your string properly. As you see in the comments above as well, brackets and dots ( and ) and . contain a special meaning when it comes to regex.

Here, this should do: (source)

function escape(s) {
  return s.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
};

Here's a working snippet:

function escape(s) {
  return s.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
};

changeFormat = function(oldValue, newValue) {
  var changeData = "http://www.semanticweb.ontology-91#rabindranath_tagore_(film)";
  var regex = new RegExp(escape(oldValue), 'g');
  console.log(regex);
  var source = changeData.replace(regex, newValue);
  console.log(source);
};


changeFormat("http://www.semanticweb.ontology-91#rabindranath_tagore_(film)", "rabindranath_tagore_(film)");
tanmay
  • 7,761
  • 2
  • 19
  • 38
  • 1
    For the record `[-\/\\^$*+?.()|[\]{}]` is completely correct. A lot of characters lose their special meaning inside square brackets and don't need to be escaped. Lots of times I see a regex with `[\.]` which can be quite difficult to read in a longer group. However, it's worth mentioning that `-` is valid to not be escaped as it is now - in the beginning of the character class. It's also valid if it's in the end. If there are any characters before AND after, then it should technically be escaped, although a `[.-+]` will still probably match only the three characters, a `[.\-+]` is better. – VLAZ Sep 14 '18 at 06:33