作为JavaScript的新手,我不知道什么时候使用它们。
有人能帮我解释一下吗?
作为JavaScript的新手,我不知道什么时候使用它们。
有人能帮我解释一下吗?
搜索函数(这里的一个描述)接受一个正则表达式,它允许您匹配更复杂的模式、不区分大小写的字符串等,而indexOf(这里的一个描述)只匹配文字字符串。但是,indexOf还允许指定开始索引。
如果没有正则表达式,indexOf和search之间就没有实际的区别。
下面的例子给出了一个现场演示:
function FromSearch() { var str = document.getElementById("demo").innerText; var n = str.search("difference"); document.getElementById("Location").innerHTML = n; } function FromindexOf() { var str = document.getElementById("demo").innerText; var n = str.indexOf("difference"); document.getElementById("Location").innerHTML = n; } <p id="demo">Without a <a href='http://www.w3schools.com/js/js_regexp.asp'>regex</a>, there is no practical difference between <a href='http://www.w3schools.com/jsref/jsref_indexof.asp'>indexOf</a> and <a href='http://www.w3schools.com/jsref/jsref_search.asp'>search</a> </p> <button onclick="FromSearch()">From search</button> <button onclick="FromindexOf()">From indexOf</button> <p>Location of difference in the above sentence is:</p> <mark id="Location"></mark>
IndexOf() -它接受字符串字面量或字符串对象,但不接受正则表达式。它还接受一个从零开始的整数值来开始搜索,例如:
“babyelephant .indexOf(“e”);//得到4 “babyelephant .indexOf(“e”,5);//搜索结果为6 从第6个位置或第5个索引开始。 Var m= /e/;“babyelephant .indexOf (m);//给出-1,因为它没有 接受正则表达式。
Search() -接受字符串字面量或字符串对象和正则表达式。但是它不接受开始搜索的索引。
indexOf()和search()
两者都有 I)返回第一个出现的搜索值 Ii)如果没有找到匹配则返回-1 让str='书已预订交付' str.indexOf('b') //返回位置8 Str.search ('b') //返回位置8
indexOf()中的特殊值 I)你可以把起始搜索位置作为第二个参数 str.indexOf('k') // 3 str.indexOf('k',4) // 11(从第4个位置开始搜索)
特殊搜索()
搜索值可以是正则表达式
str.search('book') // 8
str.search(/book/i) // 0 ( /i =case-insensitive (Book == book)
参考
除了已经提到的所有其他注意事项,indexOf在很大程度上更快,如果你不需要做时髦的正则表达式,只是做一个简单的查找,那么不要使用搜索。 robisrob想要一些证据,所以我做了一个快速测试。
Starting...
IndexOf test - loop count 10000000
IndexOf test end - duration: 4.600000023841858ms
Search test - loop count 10000000
Search test end - duration: 1221.6999999284744ms
All Done
这是一个显著的区别,只有当你要使用正则表达式时才使用搜索。
如果有人感兴趣,我可以发布测试代码。