2

I need to replace a substring from some string. I've already created corrected code for doing it. But I'm not sure it is the 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,"
Brad Mace
  • 27,194
  • 17
  • 102
  • 148
Dmytro Nesteriuk
  • 8,315
  • 1
  • 18
  • 14

4 Answers4

2

You could shorten it a little:

var reg = new RegExp('(^|,)' + substr + ',', 'gi');
Tim Pietzcker
  • 328,213
  • 58
  • 503
  • 561
1

Try this:

var reg = new RegExp("(^|,)" + substr + "(,|$)", "gi");
nickf
  • 537,072
  • 198
  • 649
  • 721
1

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
  • 155,703
  • 32
  • 311
  • 293
0

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 :)

Community
  • 1
  • 1
Mike
  • 4,542
  • 1
  • 26
  • 29