10

How do I remove double or multiple underscores in a string using JavaScript?

E.g.

stack__overflow___website

I will need to eliminate the __ and replace it with a single _.

ROMANIA_engineer
  • 51,252
  • 26
  • 196
  • 186
nhoyti
  • 1,145
  • 2
  • 20
  • 41

2 Answers2

16

You can use replace() with a regex to match consecutive underscores:

'stack__overflow___website'.replace(/_+/g, '_')
techfoobar
  • 63,712
  • 13
  • 108
  • 129
  • thank you! here's what i got from your code var _removeUnderscores = _convertLowerCase.replace(/_+/g, '_'); – nhoyti Feb 19 '14 at 12:11
3
var myString = "stack__overflow___website",
    myFormattedString = myString.split('__').join('_');
Tim Vermaelen
  • 6,501
  • 1
  • 24
  • 37