Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

334
Views
Regexp remove duplicate whitespace leaving only 1 or 2 occurences

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.

about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

You can replace matches of

(?<=\s)\s+/

with a space.

Demo

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.

about 4 years ago · Juan Pablo Isaza Report

0

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

about 4 years ago · Juan Pablo Isaza Report

0

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

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!