Remove whitespaces inside a string in javascript

耗尽温柔 提交于 2019-12-17 06:31:22

问题


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.


回答1:


For space-character removal use

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

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




回答2:


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.




回答3:


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>


来源:https://stackoverflow.com/questions/10800355/remove-whitespaces-inside-a-string-in-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!