Replace space with underscore JavaScript - All / Multiple Spaces

Sh Raj - Feb 4 '22 - - Dev Community

Replacing first space

If you are using it will only replace the first space found.

'Hello World'.replace(' ', '_'); //Output :- 'Hello_World'

'Hello My World'.replace(' ', '_'); //Output :- 'Hello_My World'
Enter fullscreen mode Exit fullscreen mode

Replacing every space with underscore

  • 1. Using text.replace(/ /g,"_");

Here you can replace all the spaces with underscore and if you have multiple spaces in string it will replace it with multiple underscores.

'frfr frrf f4w'.replace(/ /g,"_");//Output :- 'frfr_frrf_f4w'

'foo  foo'.replace(/ /g,"_");//Output :- 'foo__foo'
Enter fullscreen mode Exit fullscreen mode
  • 2. Using text.replace(/\s+/g, '_');

Here you can replace all the spaces with underscore and if you have multiple spaces in string it will replace it with single underscores.


'Hallo     World'.replace(/\s+/g, '_');//Output :- 'Hallo_World'

Enter fullscreen mode Exit fullscreen mode

That's all. Follow My Account to get more...

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .