字符串截取:
var str = "abcdefg";
console.log(str.slice(4));
console.log(str.substring(4));
console.log(str.substr(4));
console.log(str.slice(4,7));
console.log(str.substring(4,7));
console.log(str.substr(4,3));
以上打印出都是//efg
console.log(str.slice(-3));//efg 7+(-3)=4 相当于slice(4)
console.log(str.substring(-3)); //abcdefg 参数为负数会返回全部字符串
console.log(str.substr(-3)); //efg 7+(-3)=4 相当于substr(4)
console.log(str.slice(3,-3)); //'d' 相当于slice(3,4)
console.log(str.substring(3,-3)); //abc 第二个参数会转换成0, 相当于substring(0,3)
console.log(str.substr(3,-3)); //'' 第二个参数会转换成0,代表0个,所以为空
var str1 = "hello world";
console.log(str1.indexOf("o")); //4
console.log(str1.lastIndexOf("o")); //7
去前后空格:
var str2 = " hello world ";
console.log(str2.trim()); //"hello world"
字符串大小写转换:
console.log(str.toLocaleUpperCase());
console.log(str.toLocaleLowerCase());
console.log(str.toLowerCase());
console.log(str.toUpperCase());
字符串的模式匹配方法:
var text = "cat, bat, set, fat";
var pattern = /.at/;
var matches = text.match(pattern);//和pattern.exec(text)相同
console.log(matches.index);
console.log(matches[0]);
console.log(pattern.lastIndex);
match返回了一个数组
var pos = text.search(/at/); //search返回第一个匹配到的索引,有且只有一个参数
console.log(pos); //1
var result = text.replace("at","ond");
console.log(result); //"cond, bat, set, fat"
result = text.replace(/at/g,"ond")
console.log(result);//"cond, bond, sond, fond"
比较字符串:
var strValue = "yellow";
console.log(strValue.localeCompare("brick")); //1
console.log(strValue.localeCompare("yellow")); //0
console.log(strValue.localeCompare("zoo")); //-1
字符串编码转换成字符串:
console.log(String.fromCharCode(104,101,108,108,111));//hello
2960



被折叠的 条评论
为什么被折叠?



