ARTICLE DETAIL

资讯详情

深耕网站建设、视觉设计与SEO优化的一线实战洞察。

8-2 substring、slice、substr、indexOf、lastlndexOf、search、match、startsWith、endsWith、includes字符串处理之切片与搜索

8-2 substring、slice、substr、indexOf、lastlndexOf、search、match、startsWith、endsWith、includes字符串处理之切片与搜索

一、函数

1.提取字符串函数

[]

按索引方式提取

语法:字符串[2]

substring

按起止位置提取

语法:字符串.substring(1,4)

slice

按起止位置提取(可为负数)

语法:字符串.slice(1,-4)

substr

按起始位置和字符数提取

语法:字符串.substr(3,2)

2.搜索字符串函数

indexOf

搜索指定字符串的第1个位置

语法:字符串.indexOf("o")

lastIndexOf

搜索指定字符串的最后1个位置

语法:字符串.lastIndexOf("o")

search

搜索指定字符串的第1个位置(支持正则)

语法:字符串.search("o")

match

搜索指定字符串的数据(支持正则)返回数组

语法:var 数组=字符串.match("o")

startsWith(

判断搜索字符串是否是在开头

语法:字符串.startsWith("H")

endsWith

判断搜索字符串是否是在结尾

语法:字符串.endsWith("!")

includes

判断搜索字符串是否存在

语法:字符串.includes("o")

二、函数测试

function test(){

var s="Hello,WPS-JS宏,good!"

//提取字符串

Console.log(s[2]);//按索引方式提取

//结果:l

Console.log(s.substring(1,4));//按起止位置提取

//结果:ell

Console.log(s.slice(1,-4));//按起止位置提取(可为负数)

//结果:ello,WPS-JS宏,g

Console.log(s.substr(3,2));//按起始位置和字符数提取

//结果:lo

//搜索字符串

Console.log(s.indexOf("o"));//搜索指定字符串的第1个位置

//结果:4

Console.log(s.lastIndexOf("o"));//搜索指定字符串的最后1个位置

//结果:16

Console.log(s.search("o"));//搜索指定字符串的第1个位置(支持正则)

//结果:4

var arr=s.match("o")//搜索指定字符串的数据(支持正则)返回数组

Console.log(JSON.stringify(arr));//因返回的是数组,所以要用JSON.stringify打印出来

//结果:true

Console.log(s.startsWith("H"));//判断搜索字符串是否是在开头

//结果:true

Console.log(s.endsWith("!"))//判断搜索字符串是否是在结尾

//结果:true

Console.log(s.includes("o"))//判断搜索字符串是否存在

//结果:true

}

//8-2substring、slice、substr、indexOf、lastlndexOf、search、match、startsWith、endsWith、includes字符串处理之切片与搜索 function test(){ var s="Hello,WPS-JS宏,good!" //提取字符串 Console.log(s[2]);//按索引方式提取 //结果:l Console.log(s.substring(1,4));//按起止位置提取 //结果:ell Console.log(s.slice(1,-4));//按起止位置提取(可为负数) //结果:ello,WPS-JS宏,g Console.log(s.substr(3,2));//按起始位置和字符数提取 //结果:lo //搜索字符串 Console.log(s.indexOf("o"));//搜索指定字符串的第1个位置 //结果:4 Console.log(s.lastIndexOf("o"));//搜索指定字符串的最后1个位置 //结果:16 Console.log(s.search("o"));//搜索指定字符串的第1个位置(支持正则) //结果:4 var arr=s.match("o")//搜索指定字符串的数据(支持正则)返回数组 Console.log(JSON.stringify(arr));//因返回的是数组,所以要用JSON.stringify打印出来 //结果:true Console.log(s.startsWith("H"));//判断搜索字符串是否是在开头 //结果:true Console.log(s.endsWith("!"))//判断搜索字符串是否是在结尾 //结果:true Console.log(s.includes("o"))//判断搜索字符串是否存在 //结果:true }
返回列表