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


You can shorten it a bit:



var reg = new RegExp('(^|,)' + substr + ',', 'gi');

      

+2


a source


Try the following:



var reg = new RegExp("(^|,)" + substr + "(,|$)", "gi");

      

+1


a source


If your substring is not programmed or based on user input, it is easier to read in my opinion if you are defining a regex in javascript with operators / /

.

So you can override reg

as:

reg = /,ruby,|^ruby,/gi;

      

+1


a source


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







All Articles