0

var str = 'abc 123 hello xyz';

How to concat above string to abc123helloxyz? I tried to trim but it left spaces still between characters. I can't use split(' ') too as the space is not one some time.

2
  • 2
    str.replace(/\s+/g, ""); Commented Jul 27, 2016 at 3:13
  • by the way, concat is not the correct term. concat is short for concatenate - to link together, unite in series or chain, and in programming, usually refers to adding stuff to the "end" of existing stuff Commented Jul 27, 2016 at 3:25

4 Answers 4

2

You might use a regex successfully. \s checks for the occurences for any white spaced charachters. + accounts for more than once occurences of spaces. and `/g' to check for continue searching even after the first occurences is found.

var str = 'abc 123 hello     xyz';
str = str.replace(/\s+/g, "");
console.log(str);

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

3 Comments

\s for whitespace?
Yes, \s match any white space character [\r\n\t\f ]. Now it means only one character. so we add \s+ to denote there can be many adjacent spaces, find them all.
Try this regex tool. regex101.com paste the regex there, play with it and see how it varies along with the explanation.
1

Use a regex.

var newstr = str.replace(/ +/g, '')

This will replace any number of spaces with an empty string. You can also expand it to include other whitespace characters like so

var newstr = str.replace(/[ \n\t\r]+/g, '')

Comments

1

Replace the spaces in the string:

str = str.replace(" ", "");

Edit: as has been brought to my attention, this only replaces the first occurrence of the space character. Using regex as per the other answers is indeed the correct way to do it.

1 Comment

This only replaces the first space.
0

The cleanest way is to use the following regex:

\s means "one space", and \s+ means "one or more spaces".

/g flag means (replace all occurrences) and replace with the empty string.

var str = 'abc 123 hello     xyz';
console.log("Before: " + str);
str = str.replace(/\s+/g, "");
console.log("After: " + str);

Comments

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.