Remove whitespaces inside a string in javascript

JavascriptHtmlTrim

Javascript Problem Overview


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.

Javascript Solutions


Solution 1 - Javascript

For space-character removal use

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

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

Solution 2 - Javascript

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

Solution 3 - Javascript

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.

Solution 4 - Javascript

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>

Solution 5 - Javascript

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.

Solution 6 - Javascript

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 ? "))

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionHern&#225;n EcheView Question on Stackoverflow
Solution 1 - JavascriptHenrik AnderssonView Answer on Stackoverflow
Solution 2 - JavascriptArlanGView Answer on Stackoverflow
Solution 3 - JavascriptJohn CondeView Answer on Stackoverflow
Solution 4 - JavascriptJSON C11View Answer on Stackoverflow
Solution 5 - JavascriptSayed KazimiView Answer on Stackoverflow
Solution 6 - JavascriptLars FliegerView Answer on Stackoverflow