如果有人可以帮助我想出一个可以在 href 中查找模式的正则表达式,我将不胜感激。模式是查找查询字符串hint=value&,然后将其替换为新值hint=value2&。因此,如果存在更多查询字符串或提示值结尾,则该模式应以提示开头并以 & 结尾。
我不想使用 jquery 外部库 (purl)。任何帮助将不胜感激。
最佳答案
您可以使用正向前瞻并检查 &
或字符串结尾。
hint=(.*?)(?=&|$)
由于我们使用的是前瞻,这意味着替换不需要在末尾包含 &
。如果 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
关于javascript - 正则表达式 javascript 查找具有开始和结束模式的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43164809/