**String类型常用的方法,尤其是获取子串的方法汇总,注意差异**
var str = "Hello world";
// 拼接的方法
console.log(str.concat(" ", "!")); // 输出 Hello world !
// 更好的方式
console.log(str + " !"); // 输出 Hello world !
// 获取子串的方法 三种
console.log(str.slice(1, 4)); // 输出 ell
// .slice(子串开始位置, 子串结束位置)
console.log(str.substring(1, 4)); // 输出 ell
// .substring(子串开始位置, 子串结束位置)
console.log(str.substr(1, 4)); // 输出 ello
// .substr(子串开始位置, 子串长度)
// 这三种方法对 参数为负数的解析形式不同
console.log(str.slice(-3)); // 输出 rld
console.log(str.slice(1, -2)); // 输出 ello wor
console.log(str.slice(-10, -1)); // 输出 ello worl
// .slice 方法直接将 负数与字符串的长度相加
console.log(str.substring(-3)); // 输出 Hello world
console.log(str.substring(1, -2)); // 输出 H
console.log(str.substring(-10, -1)); // 输出 ""
// .substring 方法直接将 负数解释为0
console.log(str.substr(-3)); // 输出 rld
console.log(str.substr(1, -2)); // 输出 ""
console.log(str.substr(-10, -1)); // 输出 ""
// .substr 方法 第一个参数若为负数则与字符串长度相加,第二个参数若为负数直接解释为0
String类型常用的方法汇总
最新推荐文章于 2024-08-24 20:22:46 发布