JavaScript-字符串常用方法

发布于 2019-05-18  9 次阅读


获取字符串长度 .length

let str = "abcd";
    console.log(str.length);

获取某个字符[索引] /charAt

let str = "abcd";
    // let ch =str[1];是有兼容性问题的,只能在高级浏览器使用
    let ch = str.charAt(1);
    console.log(ch);

字符串查找 indexOf / lastIndexOf / includes

let str = "abacdf";
    // let index = str.lastIndexOf("c");
    let result = str.includes("c")
    console.log(result);

字符串拼接 concat / +

let str1 = "www";
    let str2 = "it666";
    // let str = str1.concat(str2);
    console.log(str);

截取子串

let str = "abcdef";
    // let subStr = str.slice(1,3);
    // let subStr = str.substring(1,3);
    let subStr = str.substr(1,3);//截取从1开始截取三个
    console.log(subStr);

字符串切割

let arr = [1,3,5];
    //let str = arr.join("-");
    //console.log(str);
    let str = "1+3+5";
    let arr = str.split("+");
    console.log(arr);

判断是否以指定字符串开头 ES6

 let str = "www.yfblog.top";
    // let str1 = str.startsWith("www");

    console.log(str1);

判断是否以指定字符串结尾 ES6

let str = "www.yfblog.top";
    let str1 = str.endsWith("top");
    console.log(str1);

字符串模板 ES6

//let str = "";
//let str = '';
//let str = `www`;
let name = "hjs";
let age = 18;
// let str = "我的名字是" + name + ",我的年龄是" + age;
let str = `我的名字是${name},我的年龄是${age}`;
console.log(str);

改变思想才能改变我们的人生