Reputation: 129
I want to be able to split a string from a repeating pattern. For exemple:
id||eq||2,id||eq||1
will give me id||eq||2
and id||eq||1
this is easy because the separator is ,
. But unfortunately I can have the separator inside the splitted part:
id||eq||2,2,id||eq||1
and I would like to get id||eq||2,2
and id||eq||1
I tried something like this: (\w+\|{2}\w+\|{2}[\w,]+,?)
But it always take the first part of the next group and not the second group
id||eq||1,2,id||eq||2,1
I'm out of ideas, if some of you can help me ?
EDIT
To be more precise, I want to get an array of objects (lets call it RequestFilter[]) from an url (and the param in the url is already an array).
An object RequestFilter looks like this:
field
which is a string and can only contain alphanumeric charstype
which is an enum, can either contain only alphanumeric charsfilter
which can be any char ( like ,
)which give me this in the url: ?filter[]=field||type||filter
today I already get RequestFilter
from an url, but now I have to get an array of RequestFilter
. I could use any separator, but because the attribute filter
can be anything there will always be a risk of conflict with it while splitting.
some more examples of strings I can have and the expected RequestFilter[]:
name||cont||pier
[{field: 'name', type: 'cont', filter: 'pier'}]
name||cont||a,id||in||2,3
[{field: 'name', type: 'cont', filter: 'pier'},{field: 'id', type: 'in', filter: '2,3'}]
id||in||2,3,4,5,address||eq||Paris,France
[{field: 'id', type: 'in', filter: '2,3,4,5'},{field: 'address', type: 'eq', filter: 'Paris,France'}]
EDIT 2
I was pretty sure it was possible to handle it with Regex but if you think it's not possible just tell me and I will try to find another way to handle it.
Upvotes: 4
Views: 132
Reputation: 327
str = 'id||eq||2,2,id||eq||1'
splitted = str.split('id||eq||')
splitted.forEach(function(item, index, arr) {
arr[index]= 'id||eq||'+item;
})
splitted.shift()
console.log(splitted)
Upvotes: 1
Reputation: 12993
A solution using Negative lookahead assertion:
const str = 'id||eq||2,id||eq||1';
const str2 = 'id||eq||2,2,id||eq||1';
console.log(
str.split(/(?!,\d),/)
)
console.log(
str2.split(/(?!,\d),/)
)
Upvotes: 2
Reputation: 15464
You can split it by ',id' and then do some manipulations like below
let str='id||eq||2,2,id||eq||1'
//split by ',id'
let arr=str.split(',id');
//join with fixed pattern
let result=arr.join('___id');
//split with fix pattern again
let final_arr=result.split('___');
console.log(final_arr);
Upvotes: 0