includes函数语法str.includes(searchString
includes 函数 语法
<span>str</span><span>.includes</span>(<span>searchString</span><span>[, position]</span>)
includes() 方法用于判断一个字符串是否包含在另一个字符串中,根据情况返回 true 或 false。
includes() 方法是区分大小写的,例如,下面的表达式会返回 false :
<span>\'Blue Whale\'</span>.includes(<span>\'blue\'</span>); <span>//</span> returns <span>false</span>
兼容补丁(polyfill)
<span>if</span> (!<span>String</span>.prototype.includes) { <span>String</span>.prototype.includes = <span><span>function</span>(<span>search, start</span>) </span>{ <span>\'use strict\'</span>; <span>if</span> (<span>typeof</span> start !== <span>\'number\'</span>) { start = <span>0</span>; } <span>if</span> (start + search.length > <span>this</span>.length) { <span>return</span> <span>false</span>; } <span>else</span> { <span>return</span> <span>this</span>.indexOf(search, start) !== <span>-1</span>; } };}
示例
<span>var</span> str = <span>\'To be, or not to be, that is the question.\'</span>;<span>console</span>.log(str.includes(<span>\'To be\'</span>)); <span>// true</span><span>console</span>.log(str.includes(<span>\'question\'</span>)); <span>// true</span><span>console</span>.log(str.includes(<span>\'nonexistent\'</span>)); <span>// false</span><span>console</span>.log(str.includes(<span>\'To be\'</span>, <span>1</span>)); <span>// false</span><span>console</span>.log(str.includes(<span>\'TO BE\'</span>)); <span>// false</span>
indexOf 函数语法
<span>str</span><span>.indexOf</span>(<span>searchValue</span> <span>[, fromIndex]</span>)
参数
searchValue
要被查找的字符串值。
如果没有提供确切地提供字符串,searchValue 会被强制设置为 “undefined”, 然后在当前字符串中查找这个值。
举个例子:’undefined’.indexOf() 将会返回0,因为 undefined 在位置0处被找到,但是 ‘undefine’.indexOf() 将会返回 -1 ,因为字符串 ‘undefined’ 未被找到。
fromIndex 可选
数字表示开始查找的位置。可以是任意整数,默认值为 0。
如果 fromIndex 的值小于 0,或者大于 str.length ,那么查找分别从 0 和str.length 开始。
举个例子,’hello world’.indexOf(‘o’, -5) 返回 4 ,因为它是从位置0处开始查找,然后 o 在位置4处被找到。另一方面,’hello world’.indexOf(‘o’, 11) (或 fromIndex 填入任何大于11的值)将会返回 -1 ,因为开始查找的位置11处,已经是这个字符串的结尾了。
示例
var anyString = \"Brave new world\";console.log(\"The index of the first w from the beginning is \" + anyString.indexOf(\"w\"));// logs 8console.log(\"The index of the first w from the <span>end</span> <span>is</span> <span>\" + anyString.lastIndexOf(\"</span>w<span>\"));// logs 10console.log(\"</span>The <span>index</span> <span>of</span> <span>\'new\'</span> <span>from</span> the <span>beginning</span> <span>is</span> <span>\" + anyString.indexOf(\"</span><span>new</span><span>\"));// logs 6console.log(\"</span>The <span>index</span> <span>of</span> <span>\'new\'</span> <span>from</span> the <span>end</span> <span>is</span> <span>\" + anyString.lastIndexOf(\"</span><span>new</span><span>\"));// logs 6</span>
本站部分文章来自网络或用户投稿,如无特殊说明或标注,均为本站原创发布。涉及资源下载的,本站旨在共享仅供大家学习与参考,如您想商用请获取官网版权,如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。