String操作
CharAt()
charAt()方法返回给定的索引位置的字符,索引从0开始;
let str="abcdefg";
conlose.log(charAt(3)); // d
concat()
将一个或多个字符串拼接成一个新的字符串。
let str="hello";
let re=str.concat(" world!");
console.log(re);// hello world!
concat()可以接收一个或多个参数;
let str="hello";
let re=str.concat(" world","!");
console.log(re);// hello world!
slice()、substr()、substring()\
slice()、substr()、substring()三个方法都返回调用他们的字符串的一个子串;
它们接受一个或两个参数。第一个表示子字符串开始的位置,第二个表示子字符串结束的位置。对于slice()和substring()第二个参数是提取结束的位置(即给位置支付前的字符会被提取出来);对于substr(),第二个参数是子串的长度。三个方法省略第二个参数意味着提取到字符串末尾。
如果参数是负数,
slice():所有负数 当做字符串长度加上负数的结果
substr():第一个参数负值当成字符串长度加上负值,第二个参数当做0
substring():会将所有负参数当做0
let str="hello world";
console.log(str.slice(3));// lo world
console.log(str.substr(3));// lo world
console.log(str.substring(3));// lo world
console.log(str.slice(3,7));// lo w
console.log(str.substr(3,7));// lo worl
console.log(str.substring(3,7));// lo w
console.log(str.slice(-3));// rld
console.log(str.substr(-3));// rld
console.log(str.substring(-3));// hello world
console.log(str.slice(3,-4));// lo w
console.log(str.substr(3,-4));//
console.log(str.substring(3,-4));// hel
indexOf()、lastindexOf()
两个方法都返回传入字符在字符串中的位置。
区别在于
indexOf():从字符串开头开始查找,从前往后;
lastindexOf():从字符串末尾开始查找,从后往前;
这两个方法接收第二个参数,表示开始查找的位置;
let str="hello world";
console.log(str.indexOf("o"));// 4
console.log(str.lastIndexOf("o"));// 7
console.log(str.indexOf("o",5));// 7
console.log(str.lastIndexOf("o",6));// 4
trim()
trim()方法会创建一个字符串的副本,删除前后所有的空格,返回结果。
trim()返回的是字符串的副本,原字符串不会受到影响。
另外 trimLeft()和trimRight()分别用于清楚字符串开头和末尾的空格。
repeat()
repeat()方法接收一个整数参数,表示需要将字符串复制多少次,然后返回拼接所有副本后的结果。
padStart(): 复制字符串,若小于指定长度,在左边填充字符。 第二个参数表示用于填充的字符;
padEnd(): 复制字符串,若小于指定长度,在右边填充字符。 第二个参数表示用于填充的字符;
字符串的大小写转换
toUpperCase(): 将字符串转换为大写;
toLowerCase(): 将字符串转换为小写。
split()
split()方法接收两个参数,第一个是一个字符串或者正则表达式,第二个是指定返回数组的最大长度(可选);方法返回字符串分割成的字符串数组。