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

171
Views
split a string in javascript based on start and end delimiters

I'm looking for a way in Javascript to split a string into an array based on "starting" and "ending" separators rather than one separator, as str.split currently does.

For example, if I have this string:

const str = '{lang}_{cmp_abbrev}_{cmp_type}_{pl_abbrev}_{w}x{h}_d{dv}c{cv}'

The result of:

str.mySplit('{', '}');

would be this:

[
    '{lang}',
    '_',
    '{cmp_abbrev}',
    '_',
    '{cmp_type}',
    '_',
    '{pl_abbrev}',
    '_',
    '{w}',
    'x',
    '{h}',
    '_d',
    '{dv}',
    'c',
    '{cv}'
]

Thus, it would take into consideration 2 characters instead of one character when determining how the string split should occur.

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

0

Regex to the rescue!

const str = '{lang}_{cmp_abbrev}_{cmp_type}_{pl_abbrev}_{w}x{h}_d{dv}c{cv}'
const values = [...str.matchAll(/\w+|\{\w+\}/g)].flat()

console.log(values)

about 4 years ago · Juan Pablo Isaza Report

0

Array#split can take regular expressions with capturing groups:

'foo{bar}baz{}!'.split(/(\{.*?\})/g)
//=> ['foo', '{bar}', 'baz', '{}', '!']

Just be aware that empty strings can be generated e.g.,

'{foo}bar{baz}'.split(/(\{.*?\})/g)
//=> ['', '{foo}', 'bar', '{baz}', '']

'{foo}{bar}{baz}'.split(/(\{.*?\})/g)
//=> ['', '{foo}', '', '{bar}', '', '{baz}', '']

But that is both normal and to be expected. If these are undesirable you can filter them out:

'{foo}{bar}{baz}'.split(/(\{.*?\})/g).filter(Boolean)
//=> ['{foo}', '{bar}', '{baz}']

With your initial string we have:

'{lang}_{cmp_abbrev}_{cmp_type}_{pl_abbrev}_{w}x{h}_d{dv}c{cv}'.split(/(\{.*?\})/g).filter(Boolean)
//=> ['{lang}', '_', '{cmp_abbrev}', '_', '{cmp_type}', '_', '{pl_abbrev}', '_', '{w}', 'x', '{h}', '_d', '{dv}', 'c', '{cv}']
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!