Remove whitespaces inside a string in javascript

后端 未结 4 1151
[愿得一人]
[愿得一人] 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:47

    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

提交回复
热议问题