1、字符串截取
(1)substring
substring(x):表示截掉前x个,得到新字符串。
substring(x,y):第一个参数是开始的下标,第二个参数是截取字符串最终的下标 (截取2个位置之间的字符串)。
let str = "0123456"
console.log(str.substring(3)) // 012
console.log(str.substring(0,3)) // 0123
(2)slice
slice(x,y),其中x和y来指定字符串截取部分,x为必须,y为可选,下标从0开始
let str = "hello world"
console.log(str.slice(1,5)) //ello
console.log(str.slice(1)) //ello world
2、字符串大小写
toUpperCase() 和 toLowerCase()
let str1 = "hello world"
let str2 = "MY HOME"
console.log(str1.toUpperCase()) //HELLO WORLD
console.log(str2.toLowerCase()) //my home
//搭配字符串截取slice函数使用
let arr = str1[0].toUpperCase() + str.slice(1)
console.log(arr) // Hello world
3、字符串拆分
扩展运算符 [...] 将字符串拆分为字符串数组
let str = "hello world"
let arr = [...str]
console.log(arr) //"h","e","l","l","o"," ","w","o","r","l","d"
4、字符串反转
reverse() 搭配扩展运算符 [...] 和 join() 函数
let str = "hello"
let arr = [...str].reverse().join("")
console.log(arr) //olleh
5、字符串替换
replace(x,y) 字符串中出现的x替换成y
let str = "hello world "
console.log(str.replace(" ",",")) //hello,world
//注意:此处只会替换首次遇到的字符,多个字符可采用正则表达式
//搭配正则表达式使用
let str = "hello world hello"
console.log(str.replace(/hello/g,hi)) //hi world hi
replace(x,function(){ }) 实现复杂替换,函数包含默认参数arguments
// 例一 将小于3的数替换成*
let str = "1,2,3,4,5,6"
let arr = str.replace(/\d+/g,function(){
return arguments[0] < 3 ? "*" : arguments[0]
})
console.log(arr) //*,*,3,4,5,6
// 例二 将"个"替换为"支"
let str = "1个,2个,3个,4个,5个"
let arr = str.replace(/(\d)+(个)/g,function(){
return arguments[1] + '支'
})
console.log(arr) //1支,2支,3支,4支,5支
6、字符串填充
padStart(number,x):字符串开头填充字符x,直至达到长度number,
padEnd(number,y):字符串末尾填充字符y,直至达到长度number
let str = "hello"
console.log(str.padStart(8,'*')) //***hello
console.log(str.padEnd(8,'*')) //hello***
7、字符串检测
(1)includes() 检查字符串是否包含特定序列
let str = "hello world moring"
console.log(str.includes("world")) //true
console.log(str.includes("word")) //false
(2)match() 字符串匹配
查找到匹配字符串的结果
若没有标志 g,方法就只执行一次匹配,找到结果就返回,不会接着去查找;若没有找到任何匹配文本,方法将会返回null;
若有标志 g,就会返回一个数组,数组中存放所有满足查找条件的信息;
let str1 = "abcdeabcde"
console.log(str1.match('a')) //'a'
console.log(str1.match(/a/g)) //['a','a']
//根据rules规则查找
let str2 = "hello world"
const rules = /[a-zA-Z]/g
console.log(str2.match(rules)) //['h', 'e', 'l', 'l', 'o', 'w', 'o', 'r', 'l', 'd']
(3)检查字符串开始或结束的特定序列
startsWith():字符串是否以特定序列开始,
endsWith():字符串是否以特定序列结束
let str = "hello world!"
console.log(str.startsWith("hello")) //true
console.log(str.endsWith("world")) //false
8、split() 分割字符串函数
(1)常规分割
let str = "hello,world,moring"
let arr1 = str.split(",")
let arr2 = str.split(",",2) //限制分割后的数组元素数量
console.log(arr1) // ["hello", "world","moring"]
console.log(arr2) // ["hello", "world"]
注意:如果将空格作为分隔符,会被多次分割,所以要注意是否有连续空格的情况
(2)利用正则表达式
let str = "hello,world;moring"
let arr = str.split(/[,;]/)
console.log(arr) //["hello","world","moring"]
9、trim() 删除空格
删除字符串中的空格符,此函数可用来避免字符串末尾的空格符造成的错误
let str = "hello "
console.log(str.trim()) //hello
不定更新,欢迎补充!!!