2017-04-02 77 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; 
} 

這將幫助你

相關問題