持续创作,加速成长!这是我参与「掘金日新计划 · 6 月更文挑战」的第7天,点击查看活动详情。
整理字符串中常用的方法......
toUpperCase方法——将字符串中的小写字母转换为大写
- 作用:将字符串中的小写字母转换为大写
- 格式:
str.toUpperCase()
var str = 'helloWORLD';
var res = str.toUpperCase();
console.log(res); // HELLOWORLD
toLowerCase方法——将字符串中的大写字母转换为小写
- 作用:将字符串中的大写字母转换为小写
- 格式:
str.toLowerCase()
var str = 'helloWORLD';
var res = str.toLowerCase();
console.log(res); // helloworld
match方法——从字符串中获取匹配到的字符
- 作用:从字符串中获取匹配到的字符
- 格式:
str.match('要匹配的字符'); - 返回值:如果包含要查找的字符,那么则返回有该字符和其下标构成的数组,如果没有要查找的字符,则返回null
var str = 'helloworld';
var res = str.match('o');
var res1 = str.match('a');
console.log(res);
console.log(res1); // null
search方法——在字符串中查找是否包含指定的字符
- 作用:在字符串中查找是否包含指定的字符,类似于indexOf
str.search('字符');- 返回值:如果包含指定字符,则返回其下标,如果没有则返回-1
var str = 'helloworld';
var res = str.search('o');
console.log(res); // 4
replace方法——将字符串中的指定字符替换为新的字符
- 作用:将字符串中的指定字符替换为新的字符
- 格式:
str.replace('旧的字符', '新的字符');
var str = 'hallo';
var res = str.replace('a', 'e');
console.log(res); // hello
split方法——将字符串转换为数组
- 作用:将字符串转换为数组
- 格式:
str.split('分隔符'); - 分隔符说明:
- 如果不写参数,那么会将整条字符串作为一个数组元素进行转换
- 如果写参数,那么参数两侧的字符会被转换为数组元素
- 如果要将字符串中的每个字符都作为一个数组元素,那么分隔符可以是空字符串
var str = 'hello';
var arr = str.split();
var arr1 = str.split('e');
var arr2 = str.split('');
console.log(arr); // ['hello']
console.log(arr1); // ['h', 'llo']
console.log(arr2); // ['h', 'e', 'l', 'l', 'o']
includes方法——判断字符串中是否包含指定的字符
- 作用:判断字符串中是否包含指定的字符,有返回true,没有返回false
- 格式:
str.includes('字符');
var str = 'helloworld';
console.log(str.includes('ow')); // true
console.log(str.includes('ww')); // false
startsWith方法——判断字符串是否以某个字符开头
- 作用:判断字符串是否以某个字符开头,如果是,则返回true、否则,返回false
- 格式:
str.startsWith('字符');
var str = 'abcdef';
var res = str.startsWith('ab');
console.log(res); // true
endsWith方法——判断字符串是否以某个字符结尾
- 作用:判断字符串是否以某个字符结尾,如果是,则返回true、否则,返回false
- 格式:
str.endsWith('字符');
var str = 'abcdef';
var res = str.endsWith('o');
console.log(res); // false
repeat方法——将字符串按照指定的次数进行重复
- 作用:将字符串按照指定的次数进行重复
- 格式:
str.repeat(次数);
var str = 'abc';
var res = str.repeat(5);
console.log(res); // abcabcabcabcabc