2016-11-24 93 views
0

如何匹配整個單詞?正則表達式返回全字匹配結果

<!DOCTYPE html> 
 
<html> 
 
<body> 
 

 
<p>Click the button to do a global search for "is" in a strisng.</p> 
 

 
<button onclick="myFunction()">Try it</button> 
 

 
<p id="demo"></p> 
 

 
<script> 
 
function myFunction() { 
 
    var str = "Is Alvin this all there is sis?"; 
 
    var patt1 = /is|alvin/gi; 
 
    var result = str.match(patt1); 
 
    document.getElementById("demo").innerHTML = result; 
 
} 
 
</script> 
 

 
</body> 
 
</html>

+0

預期是什麼? – Mritunjay

+0

寫出你期望的結果。 –

回答

1

使用\b字邊界模式。

<!DOCTYPE html> 
 
<html> 
 
<body> 
 

 
<p>Click the button to do a global search for "is" in a strisng.</p> 
 

 
<button onclick="myFunction()">Try it</button> 
 

 
<p id="demo"></p> 
 

 
<script> 
 
function myFunction() { 
 
    var str = "Is Alvin this all there is sis?"; 
 
    var patt1 = /\b(?:is|alvin)\b/gi; 
 
    var result = str.match(patt1); 
 
    document.getElementById("demo").innerHTML = result; 
 
} 
 
</script> 
 

 
</body> 
 
</html>