Is it possible to clear a line by removing duplicate spaces, tabs and line breaks, in general so that the line is like this:

var str = "test test test test"; 

and became such

 var str = "test test test test"; 

I know $.trim in jQuery for this, but it will simply remove the spaces at the end and at the beginning of the line.

Can a plugin have any, or a function?

  • I swear at the line feed in this form javascript, but you do not? - Zhukov Roman
  • I, too, but this is when you explicitly write a string to a variable, but it turned out so that I get it there in the course of the script, with all the consequences. - Smash

1 answer 1

 "test test test".replace(/\s{2,}/g, ' '); 
  • I would add a little bit: str.replace (/ [\ s {2,}] + / g, ''); - Deonis
  • but a good decision, but can it be in words? I want to understand and not stupidly copy-paste, the fact that it replaces spaces (if there are 2 or more) with one space is understandable, and the fact that g is a modifier for including line breaks and tabs, but they are not specified in the regular schedule itself, they are what themselves disappear? - Smash
  • Line breaks and tabs in a line are generally denoted \ t and \ n - Zhukov Roman
  • 2
    Namudri. str.replace(/\s+/g,' ') - KaZac
  • one
    He spoke already. \ s is not only a space. - KaZaca