如果有人可以帮助我提出一个可以在href中查找模式的正则表达式,我将不胜感激。模式是查找查询字符串hint = value&,然后将其替换为新的值hint = value2&。因此,如果有更多查询字符串或提示值的结尾,则模式应以提示开头,并以&结尾。

我不想使用jquery外部库(purl)。任何帮助都感激不尽。

最佳答案

您可以使用正向前瞻并检查&或字符串的结尾。

hint=(.*?)(?=&|$)


Live preview

由于我们使用的是前瞻性功能,因此这意味着替换不需要最后包含&。如果hint=value是最后一个查询元素,那么这可能是一个重要因素。

JavaScript中的内容如下所示:



const str = "https://www.sample.com/signup?es=click&hint=m%2A%2A%2A%2A%2A%2A%2Ai%40gmail.com&ru=%2F%22";

const replacement = "hint=newstring";

const regex = /hint=(.*?)(?=&|$)/g;

const result = str.replace(regex, replacement);

console.log(result);





给定您的示例网址,然后console.log(result)将输出:

https://www.sample.com/signup?es=click&hint=newstring&ru=%2F%22

10-05 20:53
查看更多