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

183
Views
Split a string by space but keep space after reach element - Javascript

I am trying to split a string by space but keep the space after each element. So 'This is a string' would become ['This ', 'is ', 'a ', 'string']. The input string could contain words, numbers, or special characters.

Right now I have:

var words = text.split(/(\w+\s)/).filter(x => x !== '');

The above works, but the regex split gives you ['This ', '', 'is ', '', 'a ', '', 'string'] and requires use of .filter to delete the empty string elements. I bet there is a better regex, but I'm not familiar enough with regex to figure it out.

about 4 years ago · Santiago Trujillo
1 answers
Answer question

0

You can use a lookbehind as the regular expression to split on, so that the delimiter doesn't use any characters in the string.

const text = 'This is a   string';
const words = text.split(/(?<=\s)/);
console.log(words);

about 4 years ago · Santiago Trujillo 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!