gpt4 book ai didi

javascript - 如何删除查询字符串的某些元素?

转载 作者:行者123 更新时间:2023-12-03 10:05:09 26 4
gpt4 key购买 nike

我正在编写一个脚本,您可以向它传递一个像 /search?filter1=question-1&filter2=question2 这样的网址,当问题 1 或问题 2 发生更改时,它将获取 url,并将 question-x 替换为问题值。

我想要构建的一件事是,如果该值为空,我希望它删除查询字符串部分。例如,如果 Question-1 的值为 something,但 2 还没有值,则 url 将为 /search?filter1=something

我认为可行的方法是这样的

$url.match('/([^?&]*)' + name.toSearch + '/g') // toSearch is a value like question-1

但是返回 null。谁能帮我弄清楚我需要改变什么才能获得我想要的输出?

最佳答案

Given the url /search?filter=question-1, I need to see if the element with the name question[1] has a value, if it does, replace question-1 with the value, and if it doesn't have one, remove the total filter=question-1 string.

从评论中更好地了解您的要求,我使用部分原始答案和您的一些代码完全重写了我的答案:

// Given url
var url = '/search?filter1=question-1&filter2=question-2';

// Specify the filters so no extra query string noise enters the final url
var filters = ["filter1", "filter2", "filter3"];

// Split the query string parts
var urlParts = url.split(/([&?])/);
var reassembled = [];

// Break the url parts into key:value pairs
var qs = (function(a) {
if (a === "") return {};
var b = {};
for (var i = 0; i < a.length; ++i)
{
var p=a[i].split('=', 2);
if (p.length == 1)
b[p[0]] = "";
else
b[p[0]] = decodeURIComponent(p[1].replace(/\+/g, " "));
}
return b;
})(urlParts);

// This include a param:value in the reassembled array
function includeQSParam(param, value) {
if(qs[param]) {
reassembled.push(param + "=" + value);
}
}

// Run through the filters
for(var ind in filters) {
var filter = filters[ind];

// Check that the filter exists and the supplied value is of type question-
if(qs[filter] && qs[filter].indexOf("question-") >= 0) {
// Turns question-number into question[number] so it's a valid selector.
var inputSelector = "question["+(qs[filter]).replace(/\D/g, "")+"]";

// Get the input, and the value (author-supplied code)
var $input = $('[name="' + inputSelector + '"]');

// TODO: confirm this is how you get the value
var value = $input.closest('.question').val();

if($input.length > 0 && (value !== '' && value !== undefined)) {

// Replace the parameter's original value with the question value
includeQSParam(filter, value);
} else {
// Nothing to do. This filter will be removed automatically
}
}
}

// Reassemble the URL
var fixedUrl = urlParts[0] + (reassembled.length > 0 ? "?"+reassembled.join("&") : "");

同样,这是根据我原来的答案进行修改的,因此会有一些臃肿,但我不想放弃对你的问题。

关于javascript - 如何删除查询字符串的某些元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30391745/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com