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

168
Views
RegExp / JavaScript: Split string on multiple characters, keep separators without using lookbehind

Let's say I have a string: "This is a string-thing". I want to split on both space and hyphen, but keep the separators together with the previous word => ["This ", "is ", "a ", "string-", "thing"]

I'm currently doing this using the following regExp:

string.split(/(?<=[\s-])/g)

This does what is supposed to.. at least in Chrome. As I understand Safari doesn't support lookbehind in regExp which breaks the code. Is there any way to do this without lookbehind?

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

0

You could match the words without lookbehind.

const
    string = "This is a string-thing",
    parts = string.match(/.+?([\s-]|$)/g);

console.log(parts);

about 4 years ago · Juan Pablo Isaza Report

0

You might also use split with a capture group to keep the value to split on, and remove the empty entries from the resulting array.

The pattern matches

  • ( Capture group 1
    • [^\s-]* Repeat 0+ times matching any char other than a whitespace char or -
    • [\s-] Match either a whitespace char or -
  • ) Close group 1

Note that \s can also match a newline.

const s = "This is a string-thing";
const regex = /([^\s-]*[\s-])/;
console.log(s.split(regex).filter(Boolean));

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!