Home > Net >  Split a query string by "&" but some attribute has this "&" in the value
Split a query string by "&" but some attribute has this "&" in the value

Time:07-06

I try to split an query by "&", but some attribute also has this "&" in the value, may I know how to split it? For example:

const query = "attr1=value1&attr2=va & lu&e2&attr3=value3"

May I know how to split the query into an array without splitting the "va & lu&e2":

["attr1=value1", "attr2=va &%lu&e2", "attr3=value3"]

Thanks!

CodePudding user response:

if you want to use these parameters on a query, you should use encodeURIComponent() which will escape the string so it can be used as a value in a query.

const query = "attr1="    value1   
    "&attr2="   encodeURIComponent("va & lu&e2")   
    "&attr3="   value3

This will result in the following string:

"attr1=value1&attr2=va & lu&e2&attr3=value3" 

So every '&' is encoded as '&'

To split it you can now rely on the '&' sign:

const splitArray = query.split('&')

Although, I would use the encodeURIComponent() for every query parameter value. unless I know exactly which value I use and that it doesn't need escaping.

CodePudding user response:

you could mark & differently when you are using it as a value: something like & for example and then create your own function for splitting.

like:

var acc = query[0];
var splitted = [];
for(let i = 1; i < query.length; i  ) {
    if(query[i] === '&' && query[i-1] !== '\') {
        splitted.push(acc);
        acc = "";
    } else {
        acc  = query[i];
    }
}

the code probably does not work, but hopes this can clarify something

  • Related