views:

51

answers:

4

I need to replace a substring from some string. I've already created corrected code for doing it. But I amn't sure is it best way. Please, see 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,"
+1  A: 

Try this:

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

You could shorten it a little:

var reg = new RegExp('(^|,)' + substr + ',', 'gi');
Tim Pietzcker
Thank you, it is exactly what I looked for
Dmitry Nesteruk
+1  A: 

Unless your substring is programatically generated or based on user input, it is, in my opinion, easier to read if you define a regular expression in javascript with the / / operators.

So you could redefine reg as:

reg = /,ruby,|^ruby,/gi;
Sean Vieira
yes, it is dependent on user input
Dmitry Nesteruk
A: 

To elaborate on what Sean mentions, if you are in fact programatically generating your strings, you may want to check out this SO question which has a function to escape regexp strings for javascript. Cool stuff! Good luck :)

Mike