Home > Net >  Javascript Regex Engine: Smarter way of removing double spaces and blank lines from string
Javascript Regex Engine: Smarter way of removing double spaces and blank lines from string

Time:06-22

I am using the following algorithm in order to remove double spaces and blank lines from multi-line string.

1 - First, replace two or more adjacent spaces for a single space
Regex: [ ]{2,}
Subst: " "
2 - Then, remove starting single space from the beginning of each line
Regex: ^[ ]
Subst: ""
3 - Then, remove ending single space from the end of each line
Regex: [ ]$
Subst: ""
4 - Finally, remove blank lines
Regex: (\r\n){2}
Subst: $1

What would be a smarter way of doing such task?

CodePudding user response:

You could use this regular expression:

^\s |[\t ] $|(?<=[\t ])[\t ]

With [m]ultiline option.

Demo using JavaScript:

let s = `

     This is    a  test


With several   spaces    
   
  that    should be removed   
   
`;

s = s.replace(/^\s |[\t ] $|(?<=[\t ])[\t ] /gm, "");
console.log(s);

  • Related