Remove whitespaces inside a string in javascript

后端 未结 4 1149
[愿得一人]
[愿得一人] 2020-11-29 00: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.



        
4条回答
  •  栀梦
    栀梦 (楼主)
    2020-11-29 00:41

    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;

提交回复
热议问题