Loading... ## str.charAt() 根据索引,查找对应字符,没取到是空字符(看不到);相当于下标查找 ```javascript var str = 'JavaScript’; console.log(str.charAt(4)); //S console.log(str[4]); //S console.log(str.charAt(-8)); // ``` ## str.charCodeAt() 根据索引,查找对应字符的Unicode编码 ```javascript var str = 'JavaScript'; console.log(str.charCodeAt(1)); //97 ``` ## String.fromCharCode() 根据Unicode编码,查找对应字符 ```javascript console.log(String.fromCharCode(97, 98, 99)); //abc ``` <div class="tip inlineBlock share simple"> **Unicode编码范围:** 数字:48 —— 57; 大写字母:65 —— 90; 小写字母:97 —— 122; </div> ## str.indexOf() / str.lastIndexOf() 根据指定字符串查询对应索引,返回索引或者-1; 第一个参数时要查询的字符串,第二个参数是开始查询的位置 ```javascript var str = 'JavaScript'; console.log(str.indexOf('a')); //1 console.log(str.indexOf('a', 2)); //3 console.log(str.indexOf('z')); //-1 ``` ## str.slice() 截取并拷贝【)字符串,截取失败是空字符(看不见) 第一个参数时开始位置,第二个参数时结束位置(不包括) ```javascript var str = 'JavaScript'; console.log(str.slice(0, 4)); //Java console.log(str.slice(0, -6)); //Java console.log(str.slice(11, 20)); // ``` ## str.substr() 截取字符串,截取失败是空字符(看不见) 第一个参数是开始位置,第二个参数时长度 ```javascript var str = 'JavaScript'; console.log(str.substr(0, 4)); //Java console.log(str.substr(4)); //Script ``` ## str.substring() 截取字符串 第一个参数是当前位置,第二个参数是结束的前一个 参数出现负数,默认为0;参数1>参数2时,自动换位 ```javascript var str = 'JavaScript’; console.log(str.substring(0, 4)); //Java -> 参数的前一个【) console.log(str.substring(-1, 4)); //Java -> 参数为负数,默认为0 ->即(0,4) console.log(str.substring(4, 0)); //Java -> 参数1>参数2,自动换位 ->即(0,4) console.log(str.substring(4, -1)); //Java -> 参数1>参数2自动换位即(-1,4)-> -1默认为0即(0,4) ``` <div class="tip inlineBlock share simple"> **总结:** str.slice(),str.substr(),str.substring()都是截取字符串 str.substr()第二个参数是长度,其余两个第二个参数都是位置 str.substring()中负数当0使用,且参数值大的当做第二个使用 </div> ## str.split() 合并字符 ```javascript var str = 'JavaScript’; console.log(str.split()); //["JavaScript”] console.log(str.split('')); //["J", "a", "v", "a", "S", "c", "r", "i", "p", "t”] console.log(str.split(' ')); //["JavaScript"] ``` ## str.concat() 合并字符,字符串连接 ```javascript var str = 'JavaScript’; console.log(str.concat('&', 'html')); //JavaScript&html ``` ## str.replace() 替换,参数1是旧的,参数2是新的 ```javascript var str = 'JavaScript’; console.log(str.replace('Java', 'JAVA')); //JAVAScript console.log(str.replace(/a/, '*')); //J*vaScript console.log(str.replace(/a/g, '*')); //J*v*Script ->g是全局替换 ``` ## RegExp.prototype.test() 语法:reg.test(str) 用于检测参数字符串是否符合检测表达式描述的规则,返回布尔值 ```javascript var str = 'JavaScript’; var reg = /Java/; console.log(reg.test(str)); //true var reg1 = /java/; console.log(reg1.test(str)); //false ``` ## str.toUpperCase() / str.toLowerCase() 转大写 / 转小写 ```javascript var str = 'JavaScript’; console.log(str.toUpperCase()); //JAVASCRIPT console.log(str.toLowerCase()); //javascript ``` Last modification:September 4, 2023 © Allow specification reprint Support Appreciate the author AliPayWeChat Like 如果觉得我的文章对你有用,请随意赞赏