Javascript - How to remove all extra spacing between words

前端 未结 7 1688
闹比i
闹比i 2020-12-05 02:03

How can I remove all extra space between words in a string literal?

\"some    value\"

Should become

\"some value\"
<         


        
相关标签:
7条回答
  • 2020-12-05 02:43

    In case we want to avoid the replace function with regex,

    We can achieve same result by

    str.split(' ').filter(s => s).join(' ')
    // var str = "    This    should  become   something          else   too . ";
    // result is "This should become something else too ."
    

    First, split the original string with space, then we will have empty string and words in an array. Second, filter to remain only words, then join all words with a whitespace.

    0 讨论(0)
提交回复
热议问题