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

180
Views
JS split, keep delimiter minus its first character

Original, string: "FOO,blue,FOO,yellow,red,FOO,purple,brown,blue,FOOred,orange,FOO,blue,yellow"

I'd like to convert this mixed string to an array, splitting specifically at each ,FOO, and keep FOO.

Code:

var str = "blue,FOO,yellow,red,FOO,purple,brown,blue,FOOred,orange,FOO,blue,yellow"
var regex = /(?=,FOO)/g
console.log(str.split(regex))

Codepen

Desired result:

[
'FOO,blue',
'FOO,yellow,red',
'FOO,purple,brown,blue',
'FOOred,orange',
'FOO,blue,yellow',
]

Current result:

[
'FOO,blue',
',FOO,yellow,red',
',FOO,purple,brown,blue',
',FOOred,orange',
',FOO,blue,yellow',
]

As you see, each FOO instance included the preceding comma; how can I exclude the comma in the same regex operation?

    var str = "FOO,blue,FOO,yellow,red,FOO,purple,brown,blue,FOOred,orange,FOO,blue,yellow"
    var regex = /(?=,FOO)/g
    console.log(str.split(regex))

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

0

You're only looking ahead for the comma at the moment - you need to include it in the match (outside of the lookahead) for it to be split upon and not included in the result.

var str = "FOO,blue,FOO,yellow,red,FOO,purple,brown,blue,FOOred,orange,FOO,blue,yellow"
var regex = /,(?=FOO)/g
console.log(str.split(regex))

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!