I have a string with spaces separating words. I want to replace all the spaces in the string with underscore. Please tell me any small code for that because my solution is taking too much space. Example : 'Divyanshu Singh Divyanshu Singh' output : 'Divyanshu_singh_Divyanshu_Singh'
Asked
Active
Viewed 1,679 times
-2
-
`yourString.replace(/\s+/g, "_")` – Scott Marcus Jun 01 '18 at 12:14
1 Answers
-3
Try this one:
var str = "Divyanshu Singh Divyanshu Singh";
var res = str.replace(/ /g, "_");
console.log(res);
Use, / /g is a regex (regular expression). The flag g means global and causes all matches to be replaced.

Jagjeet Singh
- 1,564
- 1
- 10
- 23

mcbrent
- 301
- 2
- 12
-
1
-
`/ /` won't find multiple spaces in a row. It should be: `/\s+/g`. – Scott Marcus Jun 01 '18 at 13:12