Home > Net >  JS split, keep delimiter minus its first character
JS split, keep delimiter minus its first character

Time:10-09

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))

CodePudding user response:

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))

  • Related