0

I have a string that has one or more {numeric}_{numeric} combinations (separated with comma) and I'd like to remove one specific combo.

('6_4,6_5,6_6').replace('\d+_5(,|$)','');

but it's not working as expected and I just do not see why. (tested in Firefox JS-Console)

MBaas
  • 5,834
  • 4
  • 36
  • 53
  • Thanks for your help, guys! Now, there's an added complication, because that '5' in the RegEx is contained in a var and needs to somehow get into the string. The obvious approach `var str = '\d+_' + 5 + '(,|$)'; var rx = new RegExp(str); '6_4,6_5,6_6'.replace(rx,'');`does not do it. Ideas? – MBaas May 20 '14 at 15:31
  • Ok, got it. http://stackoverflow.com/questions/494035/how-do-you-pass-a-variable-to-a-regular-expression-javascript :) – MBaas May 20 '14 at 15:40

4 Answers4

4

Use the /.../ delimiters in stead of '...', otherwise Javascript will try to match that String (not your expression).

'6_4,6_5,6_6'.replace(/\d+_5(,|$)/,'');

Also, the () around your initial String were unnecessary (although did not cause any problems).

Sam
  • 18,756
  • 2
  • 40
  • 65
2

You are telling it to replace a string.

.replace(/\d+_5/,'');

That should do it.

Niet the Dark Absol
  • 301,028
  • 70
  • 427
  • 540
2

Because you are passing the regexp as a string, not as a regexp. Try:

('6_4,6_5,6_6').replace(/\d+_5(,|$)/,'')
Adam
  • 6,361
  • 3
  • 34
  • 52
2

You need to use regex syntax with / and not a string

('6_4,6_5,6_6').replace(/\d+_5(,|$)/,'');
NeutronCode
  • 349
  • 2
  • 13