I’m having trouble limiting a string to prevent multiple spaces and multiple linebreaks.
This reformat is gonna happen to an input value before uploading to server.
Ex:
Input:
i am a text
with
little
to no
meaning asdas
Expected output:
i am a text
with
little
to no
meaning asdas
I googled this but it only helps with linebreaks.
str.replace(/ns*n/g, 'nn')
2
Answers
First replace more than 2 newlines with exactly 2 newlines, then replace multiple spaces with a single space?
Using
s
can also match a newline. Instead you can use a negated character class to match a whitespace character without a newline[^Sn]
You could:
Trim the string
Match 2 or more newlines followed by whitespace chars without newlines using
^(?:n[^Sn]*){2,}
and replace with a single newlineMatch 2 or more whitespace chars without a newline
[^Sn]{2,}
and replace with a single space.