Mass Exit Regular Expression

My regular expression is not so hot, so I apologize for the newest question.

I use String.replace to change the line "../../libs/bootstrap/less" only in "bootstrap". Currently my regex is as follows:

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

I believe that there should be a better way to avoid this path. Is it possible to specify a whole block of things that should be escaped as / \ "../../foo/bar/baz" /?

+4
source share
2 answers

As far as I know, regex has no global / block output. If you want to avoid escaping in this instance, you can also do the following:

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

. and / does not need to be escaped when specified in the character set []

+1
source

To simplify quoting in regular expressions, you can use the following code:

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

Then you apply it like this:

 var expr = RegExp.quote('../../libs/bootstrap/less'); mystring.replace(new RegExp(expr, 'g'), 'bootstrap'); 
0
source

Source: https://habr.com/ru/post/1440426/


All Articles