2009-08-22 171 views

回答

51

您可以使用regular expressions in Javascript做字符串的模式匹配。

例如:

var s = "hello world!"; 
if (s.match(/hello.*/)) { 
    // do something 
} 

match()的測試是非常像SQL WHERE s LIKE 'hello%'

+9

這是更好地在這裏使用'test'(應,順便說一下,會更快),因爲實際的匹配結果是不需要的。 – kangax 2009-08-22 06:02:19

12

你想使用:.indexOf("foo")然後檢查索引之前,這已經回答了。如果它>> 0,它包含該字符串。

+2

如果情況不同,它將不起作用。您需要使用:'myString.toLowerCase()的indexOf(「富」)' – CommandZ 2016-07-28 20:06:55

1

最接近你可以得到的是使用正則表達式。網絡上有很多例子(例如this one)。

14

使用String對象匹配方法:

// Match a string that ends with abc, similar to LIKE '%abc' 
if (theString.match(/^.*abc$/)) 
{ 
    /*Match found */ 
} 

// Match a string that starts with abc, similar to LIKE 'abc%' 
if (theString.match(/^abc.*$/)) 
{ 
    /*Match found */ 
} 
+0

如何如果str =「約翰·愛德華」 那我怎麼才能使用該函數的返回true匹配基於字符串的字符串,如這兩種情況下,如果str包含john => true,如果str包含edward =>也應該返回true。 – Faizan 2013-11-05 12:02:36

+0

謝謝。它非常有幫助。 – 2017-07-19 14:25:50