Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove whitespaces inside a string in javascript

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.

like image 452
Hernán Eche Avatar asked May 29 '12 13:05

Hernán Eche


People also ask

How would you remove all whitespaces from a string?

The replaceAll() method of the String class replaces each substring of this string that matches the given regular expression with the given replacement. You can remove white spaces from a string by replacing " " with "".

How do I strip a string in JavaScript?

String strip() in JavaScript We can strip a string using trim() method and can remove unnecessary trailing and leading spaces and tabs from the string. Example: HTML.

How do you remove spaces from a string in TypeScript?

Use the replace() method to remove all whitespace from a string in TypeScript, e.g. str. replace(/\s/g, '') . The replace method takes a regular expression and a replacement string as parameters. The method will return a new string with all whitespace removed.

How do you trim a character in JavaScript?

To trim leading and trailing whitespace from a string in JavaScript, you should use the String. prototype. trim() method. The trim() method removes leading and trailing whitespace characters, including tabs and newlines.


1 Answers

For space-character removal use

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

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

like image 149
Henrik Andersson Avatar answered Sep 24 '22 19:09

Henrik Andersson