-1

I Need to replace a set of characters from a string, I don't have control over the string so I can't just escape the + symbol inside the string.

So my question is, seeing as this works if I change my value to 'breeding' it does replace the string. How can I escape a string without manually escaping them? I have tried

var s = "http://example.co/kb/tags/anazolic~racing~all+articles~breeding";
var value = 'all+articles';

var find = new RegExp('\~?\\b' + value + '\\b', 'g');
var l = s.replace(find, '');
console.log(l);

DEMO: http://jsfiddle.net/AnBc6/1/

I have also tried adding: value = encodeURIComponent(value); but this didn't work either.

Any Help?

Shannon Hochkins
  • 11,763
  • 15
  • 62
  • 95
  • possible duplicate of [How to escape regular expression in javascript?](http://stackoverflow.com/questions/2593637/how-to-escape-regular-expression-in-javascript) – Dan Korn Jul 17 '14 at 22:56

2 Answers2

1

Change the third line to this:

var find = new RegExp('\~?\\b' + value.replace(/\+/g,'\\+') + '\\b', 'g');

The plus sign is a special character in a Regular Expression, so it needs to be escaped with a backslash.

(Also, I'm not sure what you mean by "stored in a variable." Everything in JavaScript is "in a variable." Or maybe you really mean, "stored in a RegExp object.")

Dan Korn
  • 1,274
  • 9
  • 14
1

So, if I understand correctly, you want to escape special regex characters.

value = value.replace(/[-\\()\[\]{}^$*+.?|]/g, '\\$&');

You could extract this to a function of course:

function escapeRegex(value) {
    return String(value).replace(/[-\\()\[\]{}^$*+.?|]/g, '\\$&');
}
Lucas Trzesniewski
  • 50,214
  • 11
  • 107
  • 158
  • In that case, this is a duplicate: http://stackoverflow.com/questions/2593637/how-to-escape-regular-expression-in-javascript – Dan Korn Jul 17 '14 at 22:53