slice()、substring()
第一个参数表示子字符串开始位置,第二个参数表示子字符串结束的位置
substr()
第二个参数表示子字符串数量
省略第二个参数都表示提取到字符串末尾
let stringValue = "hello world";
console.log(stringValue.slice(3,7)); //"lo w"
console.log(stringValue.substring(3,7)); //"lo w"
console.log(stringValue.substring(3,7)); //"lo worl"
这三个方法和concat()都不会修改原始字符串
参数为负值的情况
let stringValue = "hello world";
// 将所有负值参数当成字符串长度加上负参数值
console.log(stringValue.slice(-3)); //"rld"
//// 将所有负值参数值都转换为0
console.log(stringValue.substring(-3)); //"hello world"
// 将第一个负参数值当成字符串长度加上负参数值,将第二个负参数值转化为0
console.log(stringValue.substr(-3)); //"rld"
console.log(stringValue.slice(3,-4)); //"lo w"
console.log(stringValue.substring(3,-4)); //"hel"
// substring(3,0)等价于substring(0,3)
console.log(stringValue.substr(3,-4)); //""
字符串位置方法
let stringValue = "hello world";
console.log(stringValue.indexOf("o")); //4 从前往后找,没找到返回-1
console.log(stringValue.LastindexOf("o")); //7 从后往前找
这两个方法第二个参数表示开始搜索的位置
indexOf(“o”,6)表示从这各位置开始向后搜 //7
LastindexOf(“o”, 6)表示从这各位置开始向前搜 //4
ES6中增加了3个用于判断字符串中是否包含另一个字符串的方法:
startsWith()
endsWith()
includes()
返回 true or false
第一种和第三种方法可以接收第二个参数,从第几位开始查找
endsWith()第二个参数表示把那个位置当作末尾,或者字符串长度为这个参数
let message ="foobarbaz";
console.log(message.endsWith("bar",6)); //true
删除字符串前后所有空格
trim() //删除字符串前后所有空格,中间不删,且不修改原始字符串
trimLeft()
trimRight()
重复
let stringValue = "na ";
console.log(stringValue.repeat(4)+"hhh"); //"na na na na hhh"
填充第一个参数为扩展后长度,长度过小范围原字符串,第二个参数是填充字符,第二个参数重复填充过长会截断,
padStart(); //坐填充,默认空格
padEnd(); //右填充