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'
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'
- 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'
That's all. Follow My Account to get more...
Top comments (0)