JavaScript中常用的字符串函数
整理一下js中的字符串函数
1.chaAt()
获取某个位置上的字符
var str = "hello world, it's a nice day";
console.log(str.charAt(0));//返回h
2.charCodeAt()
获取某个位置上的字符的编码
var str = "hello world, it's a nice day";
console.log(str.charCodeAt(0));//返回104(l的编码)
3.indexOf()
从前向后查找某个字符,返回这个字符第一次出现的位置。如果没有,返回-1
var str = "hello world, it's a nice day";
console.log(str.indexOf('l'));返回2
4.lastIndexOf()
从后向前查找某个字符,返回这个字符第一次出现的位置。如果没有,返回-1
var str = "hello world, it's a nice day";
console.log(str.lastIndexOf('l'));//返回9
5.concat()
拼接字符串,将传递的参数拼接到字符串中,不改变原字符串
var str = "hello world";
console.log(str.concat(",it's a nice day"));//返回hello world,it's a nice day
6.slice()
截取指定位置字符串,参数为开始位置和结束位置,不包括结束位置,不改变原字符串
var str = "hello world";
console.log(str.slice(0, 5));//返回hello
7.substring()
和slice()的作用一样
var str = "hello world";
console.log(str.substring(0, 5));//返回hello
8.substr()
截取字符串,参数为开始位置和截取的个数,不改变原字符串
var str = "hello world";
console.log(str.substr(6, 5));
9.trim()
去除前后空格,不改变原字符串
var str = " hello world ";
console.log(str.trim());//返回hello world
10.toLowerCase()
将字符串转为小写,不改变原字符串
var str = "HELLO WORLD";
console.log(str.toLowerCase());//返回hello world
11.toUpperCase()
将字符串转为大写,不改变原字符串
var str = "hello world";
console.log(str.toUpperCase());//返回HELLO WORLD