一、indexOf()

1.定义

indexOf()方法返回String对象第一次出现指定字符串的索引,若未找到指定值,返回-1。(数组同一个概念)

2.语法

str.indexOf(searchValue[, fromIndex])
  • searchValue:字符串对象中被查找的值。
  • fromIndex:开始查找的索引,默认为0。

3.示例

let str = 'Hello, indexOf!';
console.log(str.indexOf('Hello')); // 0
console.log(str.indexOf('indexOf')); // 7
console.log(str.indexOf('l')); // 2
console.log(str.indexOf('l', 2)); // 2 加上开始查找的索引
console.log(str.indexOf('l', 3)); // 3
console.log(str.indexOf('e', 3)); // 10
console.log(str.indexOf('l', 4)); // -1
console.log(str.indexOf('world')); // -1

4.注意

区分大小写

let str = 'Hello, indexOf!';
console.log(str.indexOf('e')); // 1
console.log(str.indexOf('E')); // -1

二、includes()

1.定义

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

2.语法

str.includes(searchString[, position])
  • searchString:要搜索的字符串。
  • position:表示从哪个索引开始搜索,默认为0。

3.示例

let str = 'Hello, includes!';
console.log(str.includes('Hello')); // true
console.log(str.includes('includes')); // true
console.log(str.includes('hello')); // false
console.log(str.includes('Helle')); // false
console.log(str.includes('Helle', 1)); // false
console.log(str.includes('e', 2)); // true

三、startsWith()

1.定义

startsWith()方法用于判断一个字符串是否在另一个字符串的头部,返回true或false。

2.语法

str.startsWith(searchString[, position])

3.示例

let str = 'Hello, startsWith!';
console.log(str.startsWith('Hello')); // true
console.log(str.startsWith('H')); // true
console.log(str.startsWith('h')); // false
console.log(str.startsWith('startsWith')); // false
console.log(str.startsWith('startsWith', 7)); // true

四、endsWith()

1.定义

endsWith()方法用于判断一个字符串是否在另一个字符串的尾部,返回true或false。

2.语法

str.endsWith(searchString[, length])
  • searchString:要搜索的字符串。
  • length:作为查找字符串(str)的长度,默认是字符串本身的长度。

3.示例

let str = 'Hello, endsWith!';
console.log(str.endsWith('endsWith!')); // true
console.log(str.endsWith('EndsWith!')); // false
console.log(str.endsWith('Hello')); // false
console.log(str.endsWith('end', 10)); // true

JavaScript确定一个字符串是否包含在另一个字符串中的四种方法

最新文章

  1. Android 回到底部和返回顶部实现
  2. Java Super 覆盖方法
  3. java连接mongodb的一个奇葩问题及奇葩解决方式
  4. flex布局全解析
  5. css09浮动属性
  6. Android中的一些小知识
  7. `DevOps`相关知识搜集
  8. spring jpa 自定义查询数据库的某个字段
  9. 从头到尾解析Hash表算法
  10. Leetcode:0027
  11. vue设置初始对象时为空报错
  12. Conjob For hybris
  13. SUSE Linux Enterprise Server设置IP地址、网关、DNS(转载)
  14. FoxPro 常用内部函数
  15. windows环境下配置tornado
  16. Angular进阶教程二
  17. DNS named.conf文件详解
  18. Eclipse中安装Tomcat
  19. MiniUI级联
  20. entityframework.extended 配置mysql

热门文章

  1. jmeter 之 BSF,BeanShell(转载)
  2. vs2015+opencv-3.2.0-vc14配置
  3. Android布局中match_parent和fill_parent的差别
  4. Java 8 日期时间API使用介绍
  5. Atitit.软件开发的非功能性需求attilax 总结At
  6. SpringBoot支持https和http
  7. 配置Redmine的邮件通知功能
  8. DataUml Design 介绍10 - DataUML 1.4版本功能(增加UML活动图和用例图)
  9. java 中的valueOf方法和强转
  10. webpack issues