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
  • 26,397
  • 17
  • 98
  • 144
Dmitriy Nesteryuk
  • 8,297
  • 1
  • 17
  • 14

4 Answers4

2

You could shorten it a little:

var reg = new RegExp('(^|,)' + substr + ',', 'gi');
Tim Pietzcker
  • 313,408
  • 56
  • 485
  • 544
1

Try this:

var reg = new RegExp("(^|,)" + substr + "(,|$)", "gi");
nickf
  • 520,029
  • 197
  • 633
  • 717
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
  • 148,604
  • 32
  • 306
  • 290
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,514
  • 1
  • 25
  • 29