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'
1 Answer
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.
2 Comments
Aniruddha Gohad
will only replace the first match.
Scott Marcus
/ / won't find multiple spaces in a row. It should be: /\s+/g.
yourString.replace(/\s+/g, "_")