美文网首页
JS 字符串详解

JS 字符串详解

作者: 浅宇落 | 来源:发表于2021-05-17 10:44 被阅读0次

    增加

    concat 拼接

    var a = 'hello'
    var b = "world"
    console.log(a.concat(b)); // helloworld
    

    查询

    • slice(startIndex,endIndex)
      第二个参数 为长度
    var arr = "hello"
    console.log(arr.slice(0)); // hello
    console.log(arr.slice(0,3)); // hel
    
    • substr(index,length)
      第二个参数 为长度
    console.log(arr.substr(0,3)); // hel
    console.log(arr.substring(0,2)); // he
    
    • charAt(index) 根据下标查找对应的值
    var str = "hello"
    console.log(str.charAt(1)); // e
    
    • indexOf(value) 根据值查找对应的下标 找不到返回-1
    var arr = "hello";
    console.log(arr.indexOf('e')); // 1
    
    • lastIndexOf(value) 从后面根据值查找对应的下标 找不到返回-1
    var str = "a?f?e"
    const index = str.lastIndexOf("?") 
    console.log(index) // 3
    console.log(str.substr(0, index)) // a?f
    console.log(str.substr(index + 1)) // e
    
    • search(value) 根据值查找对应的下标 找不到返回-1
    var str = "你是谁"
     var index = str.search("她")
     console.log(index);   //  -1
    
    • includes 是否包含某位(多位)字符 返回boolean
    var arr = "hello"
    console.log(arr.includes("eh")); //false
    
    • match(value) 返回匹配的字符串,返回的是数组
    var str ="hello"
    var arr = str.match("l")
    console.log(arr);  // ["l", index: 2, input: "hello", groups: undefined]
    // 找不到返回 null
    

    length 字符串的长度

    var str = "hello"
    console.log(str.length); // 5
    

    其他方法

    • split( ) 将字符串分割成字符串数组
    var str = "hello"
    console.log(str.split()); // 将字符串转为数组 ["hello"]
    console.log(str.split("")); // ["h","e","l","l","o"]
    console.log(str.split("e"));// ["h","llo"]
    
    • replace( ) 替换字符串
    var str = "hello"
    console.log(str.replace("l","*"));  //  he*lo
    
    • trim( ) 去除字符串前后的空格
    var str = "   hello   ";
    var arr = []
    arr.push(str.trim())
    console.log(arr) // ["hello"]
    
    • startsWith( ) 以...开头的字符串
    // startsWith() 以...开头的字符串
    // endsWith()   以...结束的字符串  
    var str = "武汉"
    console.log(str.startsWith("武"))  // true
    console.log(str.endsWith("汉"))  // true
    

    字符串模板

    var str = 10;
    var b = "hello";
    console.log(str+b); // 10hello
    var sum = `${str}hello`;
    console.log(sum); // 10hello
    

    相关文章

      网友评论

          本文标题:JS 字符串详解

          本文链接:https://www.haomeiwen.com/subject/rhkqjltx.html