Home > database >  Regexp remove duplicate whitespace leaving only 1 or 2 occurences
Regexp remove duplicate whitespace leaving only 1 or 2 occurences

Time:04-25

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.

CodePudding user response:

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

CodePudding user response:

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

  • Related