js基础之String

增删改查

1
2
3
4
5
6
7
8
9
10
String.prototype.replace(substr/regexp, newsubstr/function);  // 将字符串中的substr或正则匹配的字符串,替换成newsubstr或符合function的字符串
String.prototype.concat(str1, str2, str3...); // 将多个字符串连接在一起,建议使用+代替实现
String.prototype.slice(start, end); // 返回字符串中从start开始到end结束的字符串
String.prototype.charAt(index); // 返回指定index的字符,找不到返回空字符串
String.prototype.charAt(index); // 返回指定index的字符,找不到返回空字符串
String.prototype.split(); // 将字符串按照指定字符分割成数组,字符串中无该数组时返回空数组,常与Array.prototype.join()一起使用,进行字符串与数组的转换
String.prototype.includes(str); // 查找字符串中是否有str字符,返回Boolean值
String.prototype.indexOf(); // 返回指定字符在字符串中第一次出现的的index,没有则返回-1
String.prototype.startsWith(searchStr, position); // 从position位置开始查找,字符串是否以searchStr开头,返回true/false
String.prototype.endsWith(searchStr, position); // 从position位置开始查找,字符串是否以searchStr结尾,返回true/false

填充字符串

1
2
String.prototype.padStart(length, padString); // 使用padString从原字符串左边开始填充字符串,填充长度是length。length小于原始字符串长度时不填充,length + 原数组的长度小于要填充的字符串时,截取padString的前几个字符串
String.prototype.padEnd(length, padString); // 使用padString从原字符串右边开始填充字符串

大小写转换

1
2
String.prototype.toUpperCase(); // 将字符串转换为大写
String.prototype.toLowerCase(); // 将字符串转换为小写

去除多余空格

1
2
3
String.prototype.trim(); // 去掉字符串开头和末尾的空白字符。' string with some space '.trim()  ===>  'string with some space'
String.prototype.trimLeft(); // 去掉字符串左边的空白字符。' string with some space '.trim() ===> 'string with some space '
String.prototype.trimRight(); // 去掉字符串右边的空白字符。' string with some space '.trim() ===> ' string with some space'

将字符串首字母转为大写的方法

考虑:

  • 是否需要去除多余空格;
  • 是否需要先将字符串全部转为小写
  • 是否需要将每个单词开头的字母转换为大写
  1. 使用正则:
1
2
3
4
// 第一个单词首字母
const str = 'hello world!';
str.toLowerCase().replace(/^\S/, s => s.toUpperCase());

1
2
// 每个单词首字母
str.replace(/(\s\S|^\S)/g, s => s.toUpperCase());
  1. 使用charAt
1
2
3
// 第一个单词首字母
const str = 'hello world';
str = str.replace(str.charAt(0), str.charAt(0).toUpperCase());
  1. 使用数组
1
2
3
4
5
// 每个单词首字母
const str = 'hello world';
const strs = str.split(' ');
strs.map(item => item.charAt(0).toUpperCase() + item.slice(1)).join(' ');

字符串内字符数量的统计

1
2
3
4
5
6
7
8
9
10
11
const str = 'slkahdgkjsdsgsdgas';
const myArray =str.split('');
const res = myArray.reduce((pre, cur) => {
if (pre[cur] === undefined) {
pre[cur] = 1;
} else {
pre[cur] += 1;
}
return pre;
}, {});
console.log('res', res); // res { s: 5, l: 1, k: 2, a: 2, h: 1, d: 3, g: 3, j: 1 }

找出字符串中连续出现最多的字符和个数

1
2
3
4
5
6
7
8
9
10
const str = 'abbkejsbcccwqaa';
const myArray = str.match(/(\w)\1*/g);
const maxLength = Math.max(...myArray.map(item => item.length));
const res = myArray.reduce((pre, cur) => {
if (cur.length === maxLength) {
pre[cur] = cur.length;
}
return pre;
}, {});
console.log('res', res); // res { ccc: 3 }