js字符串

字符串常用的一些方法

        // 字符串长度
        const str = 'abcd';
        console.log(str.length);  // 4

        // 转为数组
        console.log(str.split(''));  // ['a', 'b', 'c', 'd']  可添加分隔符

        // 查找 indexOf()  返回第一次出现的下标
        console.log(str.indexOf('a'));  // 0
        console.log(str.lastIndexOf('a'));  // 0  返回最后一次出现的下标

        //拼接字符串
        const arr1 = 'efg';
        console.log(str + arr1);  // abcdefg
        

        //charAt() 返回指定索引的字符
        console.log(str.charAt(0));  // a

        // charAtCode() 返回指定索引字符的ASCII值
        console.log(str.charCodeAt(0));

        // replace() 替换
        console.log(str.replace('a','o'));  // obcd

        // search 查找
        console.log(str.search('a'));  // 0

        //截取
        //slice 
        console.log(str.slice(0,2));  // ab     两个参数都是下标 但是不包括后面的那个

        // substring
        console.log(str.substring(0,2));  // ab  也是两个参数都是下标  也不包括后面的那个下标

        // endwidth()  判断当前字符串是否以给定字符串结尾的
        console.log(str.endsWith('d'));  // true

        const str2 = ' abcd ';
        // trim() 移除首尾的空白
        console.log(str2.trim());

        // includes() 判断一个字符串是否包含在另一个字符串中
        console.log(str.includes('abcd'));  // true

版权声明:本文为qq_50983290原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。