【www.gdgbn.com--php函数】

在JavaScript Search 字符搜索[search]函数 还有一个就是indexof 功能差不多,都可以判断指定的字符是否存在了.

如果知道的东西是或不是在一个字符串可以是非常重要的。如果您有一个在线论坛,不想让人们能够创建用户,其中包括发誓的话,您可以使用搜索[search]功能找到坏字的用户名和拒绝他们的任何发现。


字符串搜索[search]功能
此字符串函数正则表达式,然后检查该字符串,看看是否有任何匹配的表达。如果有一场比赛,它将会传回的位置,在一连串的比赛被发现。如果没有匹配,将返回-1 。我们将不会进入非常深入的正则表达式,但我们将告诉您如何寻找的话在一个字符串。

搜索[search]功能的正则表达式
最重要的事情时,要记住建立一个经常性的表达,它必须与周围斜线/正则表达式/ 。随着知识让我们搜索[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]
另一个基本的工具正则表达式是管字符“ | ” (它的下方的退关键标准键盘)你可以寻找替代字/ 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

本文来源:http://www.gdgbn.com/jiaocheng/18026/