slice
截取字符串
-
含头不含尾
-
结束索引不写,就直接截取末尾
var str = 'hello world'
// 使用 slice 截取字符串 var res = str.slice(1, 4) //ell console.log(res); //没有结束的索引直接截取到末尾 var res1 = str.slice(1) //ello world console.log(res1);
split
var str = 'hello world'
// 使用 split 切割成一个数组
var res = str.split()
console.log(res); //['hello world']
var res1 = str.split('')
console.log(res1); //['h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd']
var res2 = str.split(' ')
console.log(res2); //['hello', 'world']
indexOf
-
如果有该内容,返回字符的索引位置
-
如果没有该字符内容,返回-1
var str = 'hello world'
// 使用 indexOf 找到字符串中的某一个内容 var index = str.indexOf('l', 0) console.log(index) // 2 返回第一个找到的内容的下标后面的就不查找了
var index1 = str.indexOf('w', 3) console.log(index1); // 6 不管从那个索引开始,索引的位置不变
lastIndexOf
concat
var str = 'hello world '
var str1 = 'ni hao'
var res1 = str.concat(str1)
console.log(res1); // hello world ni hao
replace
字符串.repalce(被替换的内容,要替换的内容)
var str = 'hello world'
// 使用 replace 替换字符串中的内容
var res = str.replace('l', 'M')
console.log(res); // heMlo world
console.log(str); // hello world
substring
截取字符串,substring(从哪个索引开始,到哪个索引截止),含头不含尾
var str = 'hello world'
// 使用 substring截取字符串中的某一个内容
var res = str.substring(2, 8)
console.log(res); //llo wo
substr
截取字符串,substr(从哪个索引开始,截取多少个)
var str = 'hello world'
// 使用 substr截取字符串中的某一个内容
var res = str.substr(2, 7)//从索引2开始,截取7个
console.log(res); //llo wor
toLowerCase
var str = 'hello world'
// 使用 toUpperCase 转换成大写
var upper = str.toUpperCase()
console.log(upper) // HELLO WORLD
// 使用 toLowerCase 转换成小写
var lower = upper.toLowerCase()
console.log(lower) // hello world
toUpperCase
trim
去除空白内容以后的字符串
var str = ' hello world '
// 使用 trim 切割成一个数组
var res = str.trim()
console.log(res); // hello world
trimStart/ trimLeft
trimEnd/ trimRight
str.charAt(索引)
找到字符串中指定索引位置的内容返回
var str = 'hello world'
var index = str.charAt(2)
console.log(index) // l
str.charCodeAt
返回索引位置的unicode编码
var str = 'hello world'
var index = str.charCodeAt(4)
console.log(index) // 111