2016-01-11 17 views
1

我正在努力與regExp。簡單的JavaScript與URL的正則表達式

我只是想解析傳入的網址到我的應用程序。

這是我目前的正則表達式:

var regexp = new RegExp('/users','i'); 
"/users".test(regexp); //Should return true 
"https://stackoverflow.com/users/".test(regexp); //should return true 
"/users?variable1=xxx&variable2=yyy&variableN=zzzz".test(regexp); //Should return true 
"https://stackoverflow.com/users/?variable1=xxx&variable2=yyy&variableN=zzzz".test(regexp); //should return true; 
"/users?variable1=xxx&variable2=yyy&variableN=zzzz/10".test(regexp); //Should return false 
"https://stackoverflow.com/users/?variable1=xxx&variable2=yyy&variableN=zzzz/10".test(regexp); //should return false; 
"https://stackoverflow.com/users/10".test(regexp); //should return false 
"https://stackoverflow.com/users/10/contracts".test(regexp); //Should return false 
"https://stackoverflow.com/users/10/contracts/10".test(regexp); //Should return false 
"https://stackoverflow.com/users/anythingElseThatIsNotAQuestionMark".test(regexp); //Should return false 

是任何人有善心幫助我嗎?

祝你有個愉快的夜晚。

回答

0

/^\/users\/?(\?([^\/&=]+=[^\/&=]*&)*[^\/&=]+=[^\/&=]*)?$/i應該工作,並確認查詢有效:

var regexp = /^\/users\/?(\?([^\/&=]+=[^\/&=]*&)*[^\/&=]+=[^\/&=]*)?$/i; 
 

 
function test(str) { 
 
    document.write(str + ": "); 
 
    document.write(regexp.test(str)); 
 
    document.write("<br/>"); 
 
} 
 

 
test("/users"); //should return true 
 
test("https://stackoverflow.com/users/"); //should return true 
 
test("/users?variable1=xxx&variable2=yyy&variableN=zzzz"); //should return true 
 
test("https://stackoverflow.com/users/?variable1=xxx&variable2=yyy&variableN=zzzz"); //should return true 
 
test("/users?variable1=xxx&variable2=yyy&variableN=zzzz/10"); //should return false 
 
test("https://stackoverflow.com/users/?variable1=xxx&variable2=yyy&variableN=zzzz/10"); //should return false 
 
test("https://stackoverflow.com/users/10"); //should return false 
 
test("https://stackoverflow.com/users/10/contracts"); //should return false 
 
test("https://stackoverflow.com/users/10/contracts/10"); //should return false 
 
test("https://stackoverflow.com/users/anythingElseThatIsNotAQuestionMark"); //should return false

+0

謝謝你的幫助。對此,我真的非常感激。 –

2

它周圍的其他方法

test()方法執行一個定期 表達和指定的字符串之間的匹配搜索。返回true或false。

語法

regexObj.test(str) 

MDN

+0

謝謝您的幫助。 –

1

首先其RegExp.test(String)

那麼這個表達式應該做的:

/^\/users\/?(?:\?[^\/]+)?$/i 

檢查出來:https://regex101.com/r/mK8dU4/1

+0

謝謝你的幫助。對此,我真的非常感激。 –