Is it possible to improve this regex for substring?
I need to replace a substring from some string. I've already created a fixed code for this. But I'm not sure if this is the best way. Please see the code below:
var str = 'test ruby,ruby on rails,ruby,'
var substr = 'ruby';
var reg = new RegExp(',' + substr + ',|^' + substr + ',', 'gi');
str.replace(reg, ','); //returns "test ruby,ruby on rails,"
+2
a source to share
4 answers
To clarify what Sean mentions, if you are actually generating your strings programmatically, you can check out this SO question , which has a function to avoid string regex for javascript. Cool stuff! Good luck :)
0
a source to share