2016-03-11 23 views
1

我想編寫一個正則表達式來匹配我的url是否有gmt.php或不。例如:正則表達式匹配substring存在於javascript

如果我的網址http://example.com/gmt.php?a=1如果我的網址http://example.com/ac.php那麼它是假的

我想這是真的

/^([a-z0-9])$/.test('gmt.php'); 

但它並不完美。是的,我只需要正則表達式不子字符串匹配indexOf 謝謝。

+0

*「,但它不是完美的「* - 或者與你想要做的事情有任何關係...我可以建議你google一個正則表達式教程,並且你會發現這很容易實現。 – nnnnnn

回答

1

爲什麼不乾脆的indexOf

url.indexOf("gmt.php") != -1 //outputs true if it exists 

對於正則表達式(不知道爲什麼你想要的正則表達式這樣簡單的事情;))

/gmt\.php/.test('http://example.com/gmt.php?a=1 '); 

/gmt.php/.test('http://example.com/gmt.php?a=1 ');//since . is . outside [] 

/^ ([A-Z0-9])$ /測試( 'gmt.php');

但它不完美。

因爲/^([a-z0-9])$/將只匹配一個字母數字字符

+0

它不是正則表達式,我需要正則表達式。 :) –

+0

@BhuvneshGupta嘗試更新後 – gurvinder372

+0

謝謝,但我需要它,因爲一些正則表達式已經寫好了,我必須在該流程中使用:) –

0

試試這個:/gmt.php/.test(url)

<html> 
<head><title>foo</title> 
<script> 
function foo(url) { 
    alert(/gmt.php/.test(url)); 
} 
</script> 
</head> 
<body> 
<form> 
<input type="text" id="text" size="40"><input type="button" onclick="foo(document.getElementById('text').value)"> 
</form> 
</body> 
0

var reg = /^(?:https?:\/\/\w+\.\w+\/)?\w+\.\w+\?\w+\=\w+$/; 
 
var url1 = 'http://example.com/gmt.php?a=1'; 
 
var url2 = 'http://example.com/ac.php'; 
 
var url3 = 'gmt.php?a=1'; 
 
var url4 = 'gmt.php' 
 
    console.log(reg.test(url1)); 
 
    console.log(reg.test(url2)); 
 
    console.log(reg.test(url3)); 
 
    console.log(reg.test(url4));

如果有其他故障數據,請@me,