2017-04-02 152 views
2

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

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

+0

那么,为什么['str.replace( “提示=值”, “提示=数值&”)'](https://developer.mozilla.org/en-US/ docs/Web/JavaScript/Reference/Global_Objects/String/replace)不够? – Vallentin

+0

我不知道“值”,它是查询字符串之一,值可以是任何东西 – AlreadyLost

+0

对。但你怎么知道'value2'?你能举一些例子,你想要匹配一个字符串,以及你想要替换什么。 – Vallentin

回答

2

您可以使用积极的lookahead并检查&或字符串的结尾。

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 
+0

非常感谢Vallentin,它的工作原理 – AlreadyLost

+0

不客气! – Vallentin

+0

谢谢你可以帮助我理解为什么不同的正则表达式在工作,哪一个是正确的呢?我不擅长正则表达式:( – AlreadyLost

0

段:

function replaceValue(newValue, url) { 
    const regex = /\?.*?&((hint)=(.*)?&(.*))/g; 
    const matches = regex.exec(url); 
    let result = ''; 
    matches.forEach((matchString , index) => { 
     if(index === 3) { 
      result += newValue; 
     } 
     else { 
      result += matchString; 
     } 
    }); 
    return result; 
} 

这将帮助你

相关问题