0

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?

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.