I'm making a simple comment box and I want to remove excess whitespace by replacing the whitespace with only 1 or 2 tokens, whether they be newlines or spaces.
(\s){2,} is what I have so far.
However, I want to leave users with the ability to double-space their comments, and replacing this with $1, the first capture group, would reduce their lines to a single space.
So basically,
If I have 1 space or newline, then replace it with 1 space or newline.
If I have more than 1 spaces or newlines, then replace it with exactly 2 spaces or newlines.
Thanks.
You can replace matches of
(?<=\s)\s+/
with a space.
The regular expression reads, "Match one or more whitespace characters that are preceded by a whitespace character". (?<=\s) is a positive lookbehind.
Note that the characters below marked '^' are matched by the regular expression and then replaced by a single space:
Two spaces then three then four then five\n then none
^ ^^ ^^^ ^^^^
When matches are replaced by a space the string becomes the following.
Two spaces then three then four then five\n then none
Notice that the space following the newline character is the first of four whitespace characters that are matched.
text=document.getElemntById('comment_text_input').value
while(text.indexOf('\n\n\n')!=-1||text.indexOf(' ')!=-1) {
text=text.replaceAll('\n\n\n','\n\n') //it makes '\n\n\n\n\n\n' to '\n\n\n\n', the next round '\n\n\n' and finally '\n\n'
text=text.replaceAll(' ',' ') // the same with the newlines
}
document.getElemntById('comment_text_input').value=text
You can use
.replace(/(\s{2})\s+/g, '$1')
Details:
(\s{2}) - Group 1: two whitespace chars\s+ - one or more whitespaces.See the JavaScript demo:
const text = 'Abc 123\n DEF 234\n New line'
console.log(text.replace(/(\s{2})\s+/g, '$1'));