例如,我有一个使用javascript从当前URL获取的字符串
主机名/报告/ searchDate?searchOrderID =&searchDateFrom = 2018-10-16&searchDateTo = 2018-10-23&search = search&sortBy = OrderDateAsc
如何在OrderDateAsc
结尾处替换字符?例如,如果要替换OrderDateDesc
,应该如何使用Javascript进行替换? URL infront可能始终不同,它们的关键字应为&sortBy
。
请帮助,谢谢。
答案 0 :(得分:3)
var currentUrl = window.location.href;
var url = new URL(currentUrl);
var c = url.searchParams.get("sortBy");
您可以像这样获得sortBy值,也许可以为if set或not使用一些if语句,并且可以这样设置:
url.searchParams.set('sortBy',"WhateverYouWant");
还将网址转换为字符串,您可以读取参数url.searchParams.get("sortBy");
和一些if语句,
如果有更改:
url = url.Replace(sortByValue,"WhateverYouWant");
这也将起作用。 但是,如果您的字符串看起来像这样,并且您尝试更改搜索值,那么您将更改每个“搜索”值,并且它不起作用。 :
hostname/report/searchDate?searchOrderID=&searchDateFrom=2018-10-16&searchDateTo=2018-10-23&search=search&sortBy=OrderDateAsc
将搜索更改为WhateverWant
hostname/report/WhateverYouWantDate?WhateverYouWantOrderID=&WhateverYouWantDateFrom=2018-10-16&WhateverYouWantDateTo=2018-10-23&WhateverYouWant=WhateverYouWant&sortBy=OrderDateAsc
你知道,这很糟糕:)
答案 1 :(得分:0)
您可以使用以下代码来实现。
//your string
let str = "hostname/report/searchDate?searchOrderID=&searchDateFrom=2018-10-16&searchDateTo=2018-10-23&search=search&sortBy=OrderDateAsc";
//find "OrderDateAsc" and replace it with "OrderDateDesc"
str = str.replace("OrderDateAsc", "OrderDateDesc" );
答案 2 :(得分:-1)
您可以使用正则表达式并像这样替换sortBy参数值:
const url ='hostname/report/searchDate?searchOrderID=&searchDateFrom=2018-10-16&searchDateTo=2018-10-23&search=search&sortBy=OrderDateAsc';
const regex = /(&sortBy=OrderDate)(Asc)/gi;
const newUrl = url.replace(regex, '$1Desc');