项目中一些常用的和非常用的字符串方法
像slice,substring,split,indexOf,includes等方法都是常用的,一些不常用的也可以做个了解
getStr() {
//字符串的方法
let str1 = 'world';
//slice (开始的位置,结束的下标)结果不会包含结束的下标,(按下标取字符串)
let res1 = str1.slice(1, 3);
console.log('slice', res1); //or
//substring (提取字符的位置,提取的字符数)省略第二个参数会从起始位置一直到字符串结束位置(按长度取字符串)
let res2 = str1.substring(1, 3);
console.log('substring', res2, str1.substring(1)); //or orld
let str2 = 'my,you,he,she';
//split 将一个字符串分割成多个子字符串,并将结果放在一个数组中
let res3 = str2.split(',');
console.log('split', res3); //['my', 'you', 'he', 'she']
let str3 = 'OTHER';
//toLowerCase 将字符串转换为小写
console.log('toLowerCase', str3.toLowerCase()); // other
let str4 = 'family';
//toUpperCase 将字符串转换为大写。
console.log('toUpperCase', str4.toUpperCase()); //FAMILY
let obj = {
name: 'lily',
age: 39,
};
let str5 = '哈哈';
let bol = true;
//valueOf 返回对象的字符串、数值或布尔值表示
console.log('valueOf', obj.valueOf(), str5.valueOf(), bol.valueOf()); //{name: 'lily', age: 39} 哈哈 true
let num = 123;
//toString 返回对象的字符串表示。
console.log(
'toString',
num.toString(),
'abc'.toString(),
false.toString()
); //字符串类型的结果 123 abc false
let searStr = 'hthrknjh';
//search 返回字符串中第一个匹配项的索引,如果没有找到则返回-1,从字符串开头向后查找
console.log('search', searStr.search('d'), searStr.search('h')); //-1 0
//includes 返回布尔值,表示是否找到了参数字符串。
let str6 = 'hello world!';
console.log(
'includes',
str6.includes('0'),
str6.includes('o'),
str6.includes('O'),
str6.includes('l', 1)
); //false true false true
//startsWith 返回布尔值,表示参数字符串是否在源字符串的头部。
console.log('startsWith', str6.startsWith('d'), str6.startsWith('h')); //false true
//endsWith 返回布尔值,表示参数字符串是否在源字符串的尾部
console.log('endsWith', str6.endsWith('d'), str6.endsWith('!')); //false true
//repeat,返回一个新字符串,表示将原字符串重复多次
console.log('repeat', str6.repeat(3)); //'hello world!' 'hello world!' 'hello world!'
let str7 = '7';
//padStart (字符串长度,字符串前面插入的元素)
console.log(str7.padStart(5, 'ab')); //abab7
//padEnd (字符串长度,字符串后面插入的元素)
console.log(str7.padEnd(5, 'ab')); //7abab
let str8 = 'hello world';
//indexOf 返回字符串中第一个匹配项的索引,如果没有找到则返回-1,
console.log('indexOf', str8.indexOf('0'), str8.indexOf('l')); //-1 2
//concat字符串拼接
console.log('concat', 'abc'.concat('567')); //abc567
//replace 字符串替换
let str9 = 'beautiful';
let result = str9.replace('a', '9');
console.log('replace', result); //be9utiful
},