Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

176
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda