将查询字符串按“但是,有些属性具有此“”。在值中

发布于 2025-02-13 10:30:31 字数 308 浏览 2 评论 0原文

我试图通过“&”来拆分查询,但是一些属性也具有此“&”在值中,我可以知道如何将其分开吗?例如:

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

我可以知道如何将查询分为数组而不将“ VA& lu& e2”分开:

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

谢谢!

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!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

留蓝 2025-02-20 10:30:31

如果要在查询上使用这些参数,
您应该使用Encodeuricomponent(),该eNCODEROMOMPONTINT()可以逃脱字符串,以便在查询中用作值。

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

这将导致以下字符串:

"attr1=value1&attr2=va%20%26%20lu%26e2&attr3=value3" 

因此每个'&'被编码为“%26”

以拆分它,您现在可以依靠'&'符号:

const splitArray = query.split('&')

虽然,我将对每个查询参数值使用Encodeuricomponent()。除非我确切地知道我使用哪个值,并且不需要逃脱。

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.

╭ゆ眷念 2025-02-20 10:30:31

您可以标记&当您将其用作值时,有所不同:类似&例如,然后创建自己的函数以进行分裂。

像:

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];
    }
}

代码可能不起作用,但希望这可以澄清一些东西

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文