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

196
Views
use regex to replace spaces that occur with a value depending on how many spaces found

I want to use a regex that looks for spaces with a minimum length of 2 in a row, and replaces the occurrence with another value for each occurrence of the space found.

For example:

I love   to eat    cake

There are 3 spaces after love and 4 spaces after eat. I want my regex to replace occurrences of a space more than 1, and to replace it with a value for each occurrence found.

The output I am trying to go for:

I love---to eat----cake

I tried something like

myStr.replace(/ +{2,}/g, '-')
about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

You may use this code with a lookahead and a lookbehind:

const s = 'I love   to eat    cake'

var r = s.replace(/ (?= )|(?<= ) /g, '-');

console.log(r);
//=> 'I love---to eat----cake'

RegEx Details:

  • (?= ): Match a space only if that is followed by a space
  • |: OR
  • (?<= ) : Match a space only if that is preceded by a space
about 4 years ago · Juan Pablo Isaza Report

0

You can match two or more whitespaces and replace with the same amount of hyphens:

const s = 'I love   to eat    cake'
console.log(s.replace(/\s{2,}/g, (x) => '-'.repeat(x.length)) )

The same approach can be used in Python (since you asked), re.sub(r'\s{2,}', lambda x: '-' * len(x.group()), s), see the Python demo.

Also, you may replace any whitespace that is followed with a whitespace char or is preceded with whitespace using

const s = 'I love   to eat    cake'
console.log(s.replace(/\s(?=\s|(?<=\s.))/gs, '-') )
console.log(s.replace(/\s(?=\s|(?<=\s\s))/g, '-') )

See this regex demo. Here, s flag makes . match any char. g makes the regex replace all occurrences. Also,

  • \s - matches any whitespace
  • (?=\s|(?<=\s.)) - a positive lookahead that matches a location that is immediately followed with a whitespace char (\s), or (|) if it is immediately preceded with a whitespace and any one char (which is the matched whitespace). If you use (?<=\s\s) version, there is no need of s flag, \s\s just makes sure the whitespace before the matched whitespace is checked.
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!