美文网首页
JavaScript String.prototype.spli

JavaScript String.prototype.spli

作者: 椰果粒 | 来源:发表于2019-04-02 10:44 被阅读0次

    split用于将字符串分割成字符串数组

    let str = "hello world, this is my first  test!";
    console.log(str.split(" "));  // ["hello", "world,", "this", "is", "my", "first", "test!"]
    // 如果不写分割符号,默认将每个字母都分割开
    console.log(str.split(""));   // ["h", "e", "l", "l", "o", " ", "w", "o", "r", "l", "d", ",", " ", "t", "h", "i", "s", " ", "i", "s", " ", "m", "y", " ", "f", "i", "r", "s", "t", " ", "t", "e", "s", "t", "!"]
    let str1 = "|a|b|c|"
    console.log(str1.split("|")); // ["", "a", "b", "c", ""]
    // 如果要返回一部分字符
    console.log(str.split("", 4)); 
    
    // split()还可以用于正则表达式(也是返回数组)
    // 将字符串以" "一个空格分隔开
    console.log(str.split(/\s/g));  // ["hello", "world,", "this", "is", "my", "first", "test!"]
    // 将字符串以空格分割开(每个单词之间可能有多个空格)
    console.log(str.split(/\s+/g));
    

    相关文章

      网友评论

          本文标题:JavaScript String.prototype.spli

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