1. str.charAt(index); 返回子字符串 ,(index是字符下标)
const str = 'hello world';
console.log(str.charAt(0)); //h
2. str.charCodeAt(index); 返回子字符串的unicode编码
const str = 'hello world';
console.log(str.charCodeAt(0)); //104
3. String.fromCharCode(num1,num2,...,numN); 根据unicode编码返回字符串
console.log(String.fromCharCode(104)); //h
4. str.indexOf(searchString,startIndex); 返回子字符串第一次出现的位置,从startIndex开始查找,找不到时返回-1
const str = 'hello world';
console.log(str.indexOf('r', 8)); //8
console.log(str.indexOf('r', 9)); //-1
5. str.lastIndexOf(searchString,startIndex); 从后往前找子字符串,找不到时返回-1
const str = 'hello world';
console.log(str.lastIndexOf('r', 7)); //-1
console.log(str.lastIndexOf('r', 9)); //8
6.字符串之间的比较:比较第一个字符的unicode编码值,第一个字符要是相同,就比较第二个,依次往下
console.log('10000' > '2'); //false 1的unicode值比2的unicode值小
console.log('10000' > 2); //true 转成数字比较
7. 截取字符串:
- str.substring(start,end); //参数为负数的话自动转为0
- str.slice(start,end); //参数为负数则从后面开始选取
- str.substr(start,length);(不建议使用,因为ECMAscript 没有对该方法进行标准化,反对使用它。) //start参数为负数从后面开始选取,length必须为正数
const str = 'hello world';
console.log(str.substring(-2, 7)); //hello w
console.log(str.substr(-2, 1)); //l
console.log(str.slice(-2, -1)); //l
8. 字符串分割成数组。 str.split(separator,limit); 参数1指定字符串或正则,参照2指定数组的最大长度
const str = 'hello world';
console.log(str.split()); //["hello world"]
console.log(str.split('', 2)); //["h", "e"]
console.log(str.split(' ')); //["hello", "world"]
9. str.match(rgExp); 正则匹配,匹配到的字符串返回数组。
const str = 'hello world';
console.log(str.match(/l/g)); //["l", "l", "l"]
10. str.replace(rgExp/substr,replaceText) 返回替换后的字符串
const str = 'hello world';
console.log(str.replace(/l/g, 'A')); //heAAo worAd