它的问题是在 url 中使用"-"后删除所有查询字符串



在这里,我正在使用 juery 中的正则表达式从 URL 中删除查询字符串。 有两个复选框,根据要求,我正在从 URL 中删除查询字符串,其中一个复选框未选中。

例如,我的网址是这样的:

http://localhost/boat/frontend/boat_listing/loadRecord?fuels=Gasoline&engines=Jet-Drive

在这里,如果我想删除查询字符串"引擎"并想保持"燃料",它运行良好并成为 url,例如:

http://localhost/boat/frontend/boat_listing/loadRecord?fuels=Gasoline

但是当我的网址是这样的:

http://localhost/boat/frontend/boat_listing/loadRecord?engines=Jet-Drive&fuels=Gasoline

我想删除字符串"引擎"并希望保持"燃料",它删除了所有查询字符串,URL 变得如下所示:

http://localhost/boat/frontend/boat_listing/loadRecord

正如我想要的那样:

http://localhost/boat/frontend/boat_listing/loadRecord?engines=Jet-Drive

在这里,我尝试的是:

url.replace(new RegExp(key + "=\w+"),"").replace("?&","?").replace("&&","&").split('-')[0];

new RegExp('[?&]'+key+'=([^&#]*)').exec(url);
let length = url.length;
if(url.charAt(length-1)==='?')
url = url.slice(0,length-1);
if(url.charAt(length-1)==='&')
url = url.slice(0,length-1);
return url;

请建议该怎么做?

注意:网址是动态创建的。

您可能可以尝试以下代码。使用一个正则表达式实现您的功能非常困难,但我尝试使用以下逻辑实现它。

拟议程序:

1. Create a regex to capture the url in two groups.
2. Filter out the required query string by creating a dynamic regex containing your query string. That is if fuels checkbox is checked then create the regex with fuels string and when engine checkbox is checked then use engine inside the regex.

我使用了以下正则表达式:

(.*??)(.*) --> For seperating the url to two strings.
(fuels=[^\s&]*) --> Dynamic regex for filtering out the required query.

您可以在下面找到建议程序的实施:

const string = `http://localhost/boat/frontend/boat_listing/loadRecord?engines=Jet-Drive1&fuels=Petrol
http://localhost/boat/frontend/boat_listing/loadRecord?fuels=Petrol&engines=Jet-Drive2
http://localhost/boat/frontend/boat_listing/loadRecord?engines=Jet-Drive3&fuels=Gasolene`;
const regexp = /(.*??)(.*)/g;
const dynamicQueryString = "fuels"; // You can pass this string from the checked box directly.
const regex1 = new RegExp('(' + dynamicQueryString + '=[^\s&]*)', 'g');
let resultString = "";
const matches = string.matchAll(regexp);

for (const match of matches) {
let tempMatch = match[2].match(regex1);
resultString = resultString.concat(match[1] + tempMatch[0] + "n");
}
console.log(resultString);

最新更新