字符串属性方法总结

 <script>
    let message = "abcde"

    // 1.字符串的length属性
    console.log(message.length); //5
    // 2.字符串的查找方法
    console.log(message.charAt(3)); //d

    // 字符串的操作方法
    // 1.拼接方法---concat(): 用于将一个或多个字符串拼接成一个新字符串,实现了浅拷贝即不影响原字符串
    let w = "hello"
    let result = w.concat(" world")
    console.log(result); //hello world
    console.log(w); //hello

    // 接收多个参数
    let result_c = w.concat(' LiHua', '你好吗')
    console.log(result_c); //hello LiHua你好吗

    // 实现字符串拼接的更常用的方法是直接使用+操作符
    console.log(w + ' world~~~~~'); //hello world~~~~~

    // 2. 提取拆分方法----slice() substr() substring():实现浅拷贝
    let a = "hello world"
    console.log(a.slice(2)); //llo world
    console.log(a.substr(2)); //llo world
    console.log(a.substring(2)); //llo world
    console.log(a.slice(2, 5)); //llo
    console.log(a.substr(2, 5)); //llo w
    console.log(a.substring(2, 5)); //llo

    // 对负参数的行为
    console.log(a.slice(-2)); //ld
    console.log(a.substr(-2)); //ld
    // 把负参数当作0
    console.log(a.substring(-2)); //hello world

    // 将所有负值+字符串长度进行转换
    console.log(a.slice(-3, -1)); //rl
    console.log(a.substr(-3, -1)); //空,(8, 0)
    console.log(a.substring(-3, -1)); //空, (0, 0)

    // 3.位置方法----indexOf lastIndexOf,可以用来判断某个字符串是否符合预期
    let b = 'hello'

    console.log(b.indexOf("world"));//-1

    // 4.【ES6新增】包含方法----startsWith() endsWith() includes(),不考虑兼容性时,可以替代indexOf使用

    let c = 'hello'

    console.log(c.includes('world'));//false
    console.log(c.includes('hello'));//true

    // 5.去除字符串前后空格的方法
    let d = '   hello   '
    console.log(d);//   hello   
    console.log(d.trim());//hello

    // 6.拼接方法---padStart() padEnd()

    let e = 'hello'
    console.log(e.padStart(7, '哈'));//哈哈hello

    // 7.字符串迭代

    let msg = 'abcdefg'

    for (let i of msg) {
      console.log(i);
    }
    // 借助迭代属性,可以使用扩展运算符实现结构分割为数组
    console.log([...msg]);//注: split()方法也可以实现字符串到数组的转换
    console.log(msg.split(''));//["a", "b", "c", "d", "e", "f", "g"],该方法属于字符串模式匹配方法
    // 对字符串进行反转操作
    let r_msg = [...msg].reverse().join('')
    console.log(r_msg);
    console.log(...[...msg].reverse());

    // 8.模式匹配方法
    // 实现字符串部分替换操作
    let f = 'hello'

    console.log(f.replace('lo', 'mm'));

    // 9.大小写转换的方法,实现浅拷贝
    let g = 'hello'
    console.log(g.toUpperCase());
    console.log(g);

  </script>
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容