js判断字符串包含某个字符(教你查找字符串中包含某字符串)

   日期:2022-02-23     文章发布:文章发布    网络转载:生活号    
核心提示:includes函数语法 str.includes(searchString[,position]) includes()方法用于判断一个字符串是否包含在另一个字符串中,根据情况返回true或false。 includes()方法是区分大小写的,例如,下面的表达式会返回false: 'BlueWhale'.includes('blue');//returnsfalse 兼容补丁(polyf...
移动站源标题:http://mip.818114.com/news/item-175451.html

includes 函数 语法

str.includes(searchString[, position])

includes() 方法用于判断一个字符串是否包含在另一个字符串中,根据情况返回 true 或 false。

includes() 方法是区分大小写的,例如,下面的表达式会返回 false

'Blue Whale'.includes('blue'); // returns false

兼容补丁(polyfill)

if (!String.prototype.includes) {
  String.prototype.includes = function(search, start) {
    'use strict';
    if (typeof start !== 'number') {
      start = 0;
    }

    if (start + search.length > this.length) {
      return false;
    } else {
      return this.indexOf(search, start) !== -1;
    }
  };
}

示例

var str = 'To be, or not to be, that is the question.';

console.log(str.includes('To be'));       // true
console.log(str.includes('question'));    // true
console.log(str.includes('nonexistent')); // false
console.log(str.includes('To be', 1));    // false
console.log(str.includes('TO BE'));       // false

indexOf 函数语法

str.indexOf(searchValue [, fromIndex])

参数

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 8
console.log("The index of the first w from the end is " + anyString.lastIndexOf("w"));
// logs 10

console.log("The index of 'new' from the beginning is " + anyString.indexOf("new"));
// logs 6
console.log("The index of 'new' from the end is " + anyString.lastIndexOf("new"));
// logs 6
免责声明:本网部分文章和信息来源于互联网,本网转载出于传递更多信息和学习之目的,并不意味着赞同其观点或证实其内容的真实性,如有侵权请通知我们删除!(留言删除
 
 
更多>同类行业

同类新闻
最新资讯
最新发布
最受欢迎
网站首页  |  黄页  |  联系方式  |  信息  |  版权隐私  |  网站地图  |  API推送  |  网站留言  |  RSS订阅  |  违规举报  |  京ICP备2000095号