1、获取字符串长度 str.length
var str = 'hello world!how are you!';
console.log(str.length);
2、查找指定字符位置
2.1 IndexOf ()和 lastIndexOf()
var str = 'hello world!how are you!';
console.log(str.indexOf('how')) // 查找how最早出现的位置,无则返回-1
console.log(str.indexOf('h',1)) // 1表示从1开始索引(包含位置1)
console.log(str.lastIndexOf('h')) //查找h最后出现的位置,无则返回-1
2.2 search()
var str = 'hello world!how are you!';
console.log(str.search('o')) //查找o最早出现的位置,无则返回-1
indexOf() 和 search()的区别:前者可以设置起始搜索位置后者不行;而后者可以使用正则表达式前者不行;
3、截取片段
3.1 slice()
var str = 'hello world!how are you!';
console.log(str.slice(1, 3)) //查找字符串str中位置1到3的字符,对应位置无结果则返回为空
console.log(str.slice(-3, -1)) //查找倒数第3至倒数第1的字符
console.log(str.slice(5)) // 查找位置5至末尾的字符
3.2 substring()
跟slice()类似,但不支持反向位置查找且无返回为-1
3.3 substr()
var str = 'hello world!how are you!';
console.log(str.substr(1, 3)) //1指定开始查找位置,3指定查找长度
console.log(str.substr(-5, 3)) //支持反向位置查找
3.4 match()
var str = 'hello world!how are you!';
console.log(str.match('how')) //查找how匹配的字符,返回【how】
rex = /\d/mg //定义正则匹配公式,\d代表匹配数字,mg代表匹配全局多次
console.log(sms.match(rex)) // 查找对象中全部数字并返回(每次匹配结果单独返回在结果集中)
match() 和indexOf()都是查找指定字符(串),但前者是返回对应值,可以使用正则表达式查找特定特征的值