4

My regex is not so hot so apologies for the very newb question.

I'm using String.replace to change the string "../../libs/bootstrap/less" into just "bootstrap". Currently my regex looks like this:

myString.replace(\.\.\/\.\.\/libs\/bootstrap\/less/g, 'bootstrap);

I figure there has to be a better way to escape that path. Is it possible to specify a whole block of stuff to be escaped like /\"../../foo/bar/baz"/ ?

robdodson
  • 6,616
  • 5
  • 28
  • 35

2 Answers2

1

As far as I am aware, there is no global/block escape in regex. If you wanted to avoid the escaping in this instance you could alternatively do the following:

myString.replace(/([.]{2}[/]){2}libs[/]bootstrap[/]less/g, "bootstrap");

. and / don't need to be escaped when specified within a character set []

cbayram
  • 2,259
  • 11
  • 9
0

To make it easier what to quote in regular expressions you can use the following code:

RegExp.quote = function(str) {
     return str.replace(/([.?*+^$[\]\\(){}|-])/g, "\\$1");
};

Then you apply it like so:

var expr = RegExp.quote('../../libs/bootstrap/less');
mystring.replace(new RegExp(expr, 'g'), 'bootstrap');
Ja͢ck
  • 170,779
  • 38
  • 263
  • 309