2014-03-02 36 views
0

我試圖用JS替換一些URL。 我不明白,爲什麼正則表達式在這裏不匹配。 我在這個網站上測試了我的表情:http://www.regular-expressions.info/javascriptexample.html 我在這裏得到了積極的結果,但沒有在我自己的腳本中。 任何人都可以在這裏協助嗎?將var傳遞給正則表達式與URL不匹配

var pattern = new RegExp("http://www\.example\.com/out/\?url=","g"); 
var context = "http://www.example.com/out/?url=http://google.com"; 
if(context.match(pattern)) 
{ 
    context = context.replace(pattern,""); 
    alert(context); 
} 
else 
    alert("no match"); 
+2

使用'new RegExp'時需要雙重轉義。我猜測你在測試正則表達式文字的網站上。即新的RegExp(「http:// www \\ .example \\ .com/out/\\?url =」,「g」)' – Xotic750

+1

http://jsfiddle.net/Xotic750/FA64L/ – Xotic750

+1

請參閱[ 'RegExp'](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions) – Xotic750

回答

1

當使用正則表達式時,以下內容將是正確的。

var pattern = /http:\/\/www\.example\.com\/out\/\?url=/; 

當使用new RegExp

//var pattern = /http:\/\/www\.example\.com\/out\/\?url=/; 
//var pattern = new RegExp("http:\\/\\/www\\.example\\.com\\/out\\/\\?url="); 
var pattern = new RegExp("http://www\\.example\\.com/out/\\?url="); 

var context = "http://www.example.com/out/?url=http://google.com"; 

if (context.match(pattern)) { 
    context = context.replace(pattern, ""); 
    alert(context); 
} else { 
    alert("no match"); 
} 

我沒有看過該網站的鏈接,看看他們與你的輸入準確地做下面是正確的。

但基本上在使用RegExp時,您需要將任何在正則表達式字面上轉義的東西加倍轉義。 /不需要轉義符,因爲它們在使用文字時特別有用。

哦,你不需要g標誌在你的例子。

jsFiddle

+0

在「\\/out \\ /」上刪除了錯誤的轉義,我可以接受它作爲正確的答案 –

+1

這是正確的轉義,不應該是這樣的例子。 :) – Xotic750

+0

噢,如果URL總是一樣的話,那麼在不使用正則表達式的情況下可能會有更好的方法。 http://jsfiddle.net/Xotic750/6hPMV/ – Xotic750