在JavaScript Search 字元搜尋[search]函數 還有一個就是indexof 功能差不多,都可以判斷指定的字元是否存在了.
如果知道的東西是或不是在一個字串可以是非常重要的。如果您有一個線上論壇,不想讓人們能夠建立使用者,其中包括髮誓的話,您可以使用搜尋[search]功能找到壞字的使用者名稱和拒絕他們的任何發現。
字串搜尋[search]功能
此字串函數Regex,然後檢查該字串,看看是否有任何匹配的表達。如果有一場比賽,它將會傳回的位置,在一連串的比賽被發現。如果沒有匹配,將返回-1 。我們將不會進入非常深入的Regex,但我們將告訴您如何尋找的話在一個字串。
搜尋[search]功能的Regex
最重要的事情時,要記住建立一個經常性的表達,它必須與周圍斜線/Regex/ 。隨著知識讓我們搜尋[search]一個字串,看看是否一個共同的名字“亞曆克斯”是裡面。
<script type="text/javascript">
var myRegExp = /Alex/;
var string1 = "Today John went to the store and talked with Alex.";
var matchPos1 = string1.search(myRegExp);
if(matchPos1 != -1)
document.write("There was a match at position " + matchPos1);
else
document.write("There was no match in the first string");
</script>
結果:
There was a match at position 45
請注意,我們經常只是表達的名稱是“亞曆克斯” 。搜尋[search]功能然後用這個名字,看看是否“亞曆克斯”中存在的字串。比賽被發現,並擔任比賽( 45歲) ,被送回。
字串搜尋[search]功能:替代搜尋[search]
另一個基本的工具Regex是管字元“ | ” (它的下方的退關鍵標準鍵盤)你可以尋找替代字/ RegExp1 | RegExp2 / 。而不只是尋找一個詞,我們現在可以使用管道字元搜尋[search]多個字。
<script type="text/javascript">
var myRegExp = /Alex|John/;
var string1 = "Today John went to the store and talked with Alex.";
var matchPos1 = string1.search(myRegExp);
if(matchPos1 != -1)
document.write("There was a match at position " + matchPos1);
else
document.write("There was no match in the first string");
</script>
結果為6