Pierre Fiorelli
Pierre Fiorelli

Reputation: 129

How to split a string from a pattern

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:

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[]:

[{field: 'name', type: 'cont', filter: 'pier'}]

[{field: 'name', type: 'cont', filter: 'pier'},{field: 'id', type: 'in', filter: '2,3'}]

[{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

Answers (3)

DPK
DPK

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

Fraction
Fraction

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

sumit
sumit

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

Related Questions