字符串常用方法

 
  • 字符串拼接

    • concat() :对字符串进行拼接

    let num = "1";
    let num1 = num.concat("2")
    console.log(num1) //"12"
  • 字符串删除:创建原字符串的一个副本,然后在对这个副本进行删除操作

    • slice():两个参数。第一个为开始位置,第二个为结束位置

    • substr():两个参数。第一个为开始位置,第二个为总共的元素的个数

    • substring():两个参数。第一个为开始位置,第二个为结束位置

    let stringValue = "hello world";
    console.log(stringValue.slice(3)); // "lo world"
    console.log(stringValue.substring(3)); // "lo world"
    console.log(stringValue.substr(3)); // "lo world"
    console.log(stringValue.slice(3, 7)); // "lo w"
    console.log(stringValue.substring(3,7)); // "lo w"
    console.log(stringValue.substr(3, 7)); // "lo worl"
  • 修改字符串 : 创建原字符串的一个副本,然后在对这个副本进行修改操作

    • trim() : 删除前后所有的空格,再返回新的字符串

    • trimLeft() : 删除前面所有的空格,再返回新的字符串

    • trimRight() : 删除后面所有的空格,再返回新的字符串

    let str = " hello "
    let str1 = str.trim();
    console.log(str)  // " hello "
    console.log(str1) //"hello"
    • repeat(n) : 复制n次字符串,然后再拼接所有结果返回

    let str = "name";
    let str1 = str.repeat(2) //name name
    • padStart(n): 复制字符串,如果小于n, 则在字符串的前面添加字符

    let str = "name";
    let str1 = str.padStart(6, ".") // "..name"
    • padEnd(n):复制字符串,如果小于n, 则在字符串的后面添加字符

    let str = "name";
    let str1 = str.padStart(6, ".") // "name.."
    • toLowerCase() : 将字符串转化为小写

    let str = "ABC";
    let str1 = str.toLowerCase(); //"abc"
    • toUpperCase() : 将字符串转化为大写

    let str = "abc";
    let str1 = str.toLowerCase(); //"ABC" 
  • 查找字符

    • chatAt(n) : 返回 n 位置上的字符

    let str = "abcde";
    let str1 = str.charAt(2); // "c"
    • indexOf() : 从头去查找传入的字符串,返回第一个 找到这个字符串的位置(没找到返回 -1)

    let str = "abcde";
    let str1 = str.charAt("b"); // 1
    • startWith() 、includes() : 从字符串中查找传入的字符串,若有包含返回true,否则返回false

    let str = "abcdefg"
    let str1 = str.startWith("abcd") //true
    let str2 = str.includes("abcd") //true
  • 字符串转数组:split() : 将字符串按照指定的分割符拆分成数组

let str = "abcd";
let str1 = str.split("") //[a, b, c, d]
posted @ 2022-06-24 20:27  小宝想学好前端  阅读(41)  评论(0编辑  收藏  举报