12

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
  • 54,432
  • 29
  • 203
  • 199
nhoyti
  • 1,615
  • 2
  • 26
  • 42

2 Answers2

17

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

'stack__overflow___website'.replace(/_+/g, '_')
techfoobar
  • 65,616
  • 14
  • 114
  • 135
  • 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,869
  • 1
  • 25
  • 39