js字符串方法总结

发布于:2022-12-23 ⋅ 阅读:(215) ⋅ 点赞:(0)

2. 字符串分割

#### split() 用于分割字符串,执行后返回一个数组

- 参数1:是根据指定内容进行截断,并且该内容会去除

- 参数2:指定返回数组的长度,可选。若指定长度小于等于实际分割长度,则按分割结果从索引值 0 位置截取指定长度数组返回;若指定长度超出实际分割长度,则返回实际分割数组,不会额外加长。

 var str = "I, am ,a ,good ,student"

        var result = null;

        result = str.split(',');//(5) ['I', ' am ', 'a ', 'good ', 'student']

        console.log(result);

        result = str.split(',', 3);

        console.log(result);//) ['I', ' am ', 'a ']

        result = str.split(',', 13);

        console.log(result); // ['I', ' am ', 'a ', 'good ', 'student']

        result = str.split('');//值为空。截取所有字符

        console.log(result);/  /['I', ',', ' ', 'a', 'm', ' ', ',', 'a', ' ', ',', 'g', 'o', 'o', 'd', ' ', ',', 's', 't', 'u', 'd', 'e', 'n', 't']

        // 案例 1. 找出一个语句中最长的单词        

        var str1 = "I ,come ,from ,china,  I ,am ,is, a ,hansome ,man "

        var max = '';

        str1.split(',').forEach((word) => {

            if (word.length > max.length) {

                max = word

            }

            return max;

        })

        console.log(max);//hansome

本文含有隐藏内容,请 开通VIP 后查看

网站公告

今日签到

点亮在社区的每一天
去签到