简体   繁体   中英

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

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!

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%20%26%20lu%26e2&attr3=value3" 

So every '&' is encoded as '%26'

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM