-2

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
  • yourString.replace(/\s+/g, "_") Commented Jun 1, 2018 at 12:14

1 Answer 1

-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.

Sign up to request clarification or add additional context in comments.

2 Comments

will only replace the first match.
/ / won't find multiple spaces in a row. It should be: /\s+/g.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.