188

I've read this question about javascript trim, with a regex answer.

Then I expect trim to remove the inner space between Hello and World.

function myFunction() {
    alert("Hello World ".trim());
}

EDITED

Why I expected that!?

Nonsense! Obviously trim doesn't remove inner spaces!, only leading and trailing ones, that's how trim works, then this was a very wrong question, my apologies.

5
  • 17
    trim removes whitespace from the beginning and end of a string
    – Manse
    May 29, 2012 at 13:42
  • 3
    Trim removes whitespace from before and after a string. Hello World is already "trimmed'.
    – gen_Eric
    May 29, 2012 at 13:42
  • 4
    @void: That's not "trimming", that's a different problem.
    – gen_Eric
    May 29, 2012 at 13:43
  • related stackoverflow.com/questions/6623231/…
    – Adriano
    Jul 15, 2014 at 11:38
  • Heh.. "obviously" trim will trim something but not from the "middle" ... you need a stripping instead of trimming.. a nice regex like someone already pointed out :-)
    – AlexD
    Apr 6 at 20:47

7 Answers 7

382

For space-character removal use

"hello world".replace(/\s/g, "");

for all white space use the suggestion by Rocket in the comments below!

3
  • 20
    @RocketHazmat yes! the correct answer! though this might be slightly more efficient: str.replace(/\s+/g, '')
    – jackocnr
    Jan 8, 2014 at 1:47
  • @RocketHazmat : what do u mean by other white spaces? '.replace(/ /g, '')' this will remove all white spaces right? Oct 13, 2017 at 6:57
  • 4
    @PitchiahNatarajan \s will match spaces, tabs, and new lines.
    – gen_Eric
    Oct 15, 2017 at 20:13
53

You can use

"Hello World ".replace(/\s+/g, '');

trim() only removes trailing spaces on the string (first and last on the chain). In this case this regExp is faster because you can remove one or more spaces at the same time.

If you change the replacement empty string to '$', the difference becomes much clearer:

var string= '  Q  W E   R TY ';
console.log(string.replace(/\s/g, '$'));  // $$Q$$W$E$$$R$TY$
console.log(string.replace(/\s+/g, '#')); // #Q#W#E#R#TY#

Performance comparison - /\s+/g is faster. See here: http://jsperf.com/s-vs-s

Update

You can use too:

console.log(string.replaceAll(/\s/, '#')); // #Q#W#E#R#TY#

String.prototype.replaceAll()

4
  • The currently accepted answer does the same thing. Please present some relevant tests indicating this is faster than that answer by anything more than nanoseconds. Apr 10, 2020 at 12:31
  • @HereticMonkey Updated!
    – ArlanG
    Apr 14, 2020 at 14:01
  • 2
    Thank you for the example, made it crystal clear what the difference is doing.
    – Sigex
    Dec 9, 2021 at 21:53
  • 1
    please update your answer with replaceAll Mar 31 at 16:03
14

The best way is to do it this way if you only want to replace the whitespaces:

let str = " H e l l o 1  5 9   ";
let onlyCharacters = str.replaceAll(" ", "");

// onlyCharacters = Hello159

I used str.replace(/\s/g, ""); a lot but it does not work in all the browsers for example it does not work in duckduckgo in android and also it does not work in android webview.

12

Probably because you forgot to implement the solution in the accepted answer. That's the code that makes trim() work.

update

This answer only applies to older browsers. Newer browsers apparently support trim() natively.

2
6

You can use Strings replace method with a regular expression.

"Hello World ".replace(/ /g, "");

The replace() method returns a new string with some or all matches of a pattern replaced by a replacement. The pattern can be a string or a RegExp

RegExp

  • / / - Regular expression matching spaces

  • g - Global flag; find all matches rather than stopping after the first match

const str = "H    e            l l       o  World! ".replace(/ /g, "");
document.getElementById("greeting").innerText = str;
<p id="greeting"><p>

0

You could use a recursive solution:

function removeWhitespaces(string, i = 0, res = "") {
  if (i >= string.length)
    return res
  else
  if (string[i] == " ")
    return removeWhitespaces(string, i + 1, res)
  else
    return removeWhitespaces(string, i + 1, res += string[i])
}

console.log(removeWhitespaces(" Hello World,   how is it going ? "))

0

Precise answer to how to approach this depends on precise intention. To remove any and/or all white space characters you should use:

's t r i n g'.replace(\s+\g, '')

If the intention is to only remove specific types of whitespaces (ie. thin or hair spaces) they have to be listed explicitely like this:

's t r i n g'.replace(\ |\t \g, '')

However if the intention is to remove just plain spaces only, then performance wise the best solution is:

's t r i n g'.replace(' ', '')


Here is a benchmark comparing results. There is a slight performance variance amongst the regexp solutions, but its rather insignificant. However string based replace outperforms regexps in the linked benchamrk by about an order of magnitude of ops/s. (https://jsbench.me/drlfuphfhk/1)

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.