2

How can I make extra space be removed in a string in Javascript ?

For example

I have a string the following string

var string ="how    are you today";

I would like to know what function or trick I could use to dynamically remove extra space in strings in Javascript so that I can have var string ="how are you today"; instead ..

How could I do this ?

2
  • 1
    I would use a regex stackoverflow.com/questions/8150037/… Commented Mar 22, 2013 at 18:25
  • 1
    I know it's just an example but even for an example you shouldn't use a variable name like string. Commented Mar 22, 2013 at 18:26

1 Answer 1

6

Lets assume you have var myString ="how are you today";

If you just want to handle spaces:

myString.replace(/ +/g, ' ');

If you want to replace tabs and new lines as well:

myString.replace(/\s+/g, ' ');

Please note that this does not change the value of myString, but rather return a new string with the spaces removed. So to save this result you would do, for example:

var fixedString = myString.replace(/ +/g, ' ');

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

2 Comments

@kennebec Right. Corrected my answer :)
@OpherV where is the variable name of the string represented in your example ? if my string variable name is sentence .. how would you remove all the spaces in it .. sentence.replace(/ +g, ' '); ?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.