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:
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);