# JavaScript教程 - 13 字符串和正则表达式

下面介绍一下字符串常用的方法和在 JavaScript 中使用正则表达式对字符串进行处理。


# 13.1 字符串常用方法

方法有很多,先了解一下,开发的时候忘记了,可以来查看。

需要注意,字符串是不可变的,所以创建后就无法修改了,执行字符串的方法后,得到的都是一个新的字符串。


# 1 基本属性

.length:获取字符串的长度

const str = 'hello';
console.log(str.length); // 输出: 5
1
2

# 2 查找类方法

字符串本质是一个字符数组,所以有很多方法和数组相似。

'hello'  ->  ['h', 'e', 'l', 'l', 'o']
1

所以字符串可以通过下标获取对应位置的字符。

举个栗子:

let str = 'hello';
console.log(str[0]);  // h
console.log(str[1]);  // e
1
2
3
  • 能依次获取字符串中的字符。

你也可以使用 charAt(index).charAt(index) 也是返回指定位置字符。

const str = 'hello';
console.log(str.charAt(1)); // 输出: 'e'
1
2

下面再介绍一下其他常用的方法。

  • .indexOf():返回子串在字符串中第一次出现的位置,找不到返回 -1
const str = 'hello';
console.log(str.indexOf('l')); // 输出: 2
1
2

  • .lastIndexOf():返回子串在字符串中最后一次出现的位置
const str = 'hello';
console.log(str.lastIndexOf('l')); // 输出: 3
1
2

  • .includes():判断是否包含某个子串,返回布尔值
const str = 'hello';
console.log(str.includes('el')); // 输出: true
1
2

  • .startsWith():判断是否以某个子串开头
const str = 'hello';
console.log(str.startsWith('he')); // 输出: true
1
2

  • .endsWith():判断是否以某个子串结尾
const str = 'hello';
console.log(str.endsWith('lo')); // 输出: true
1
2

# 3 截取类方法

  • .slice(start, end):截取start到end区间的字符,包含start、不包含end,支持负数。start 可以大于 end(结果是空字符串)。
const str = 'hello';
console.log(str.slice(1, 4)); // 输出: 'ell'
console.log(str.slice(-4, -1)); // 'ell'(-1表示从末尾开始)
1
2
3

  • .substring(start, end):截取start到end区间的字符,包含start、不包含end,不支持负数,如果 start > end,它会自动调换两个参数
const str = 'hello';
console.log(str.substring(1, 4)); // 输出: 'ell'
1
2

# 4 修改与替换类方法

注意:替换和修改得到的都是新的字符串!

  • .toUpperCase():将字符串转为大写
const str = 'hello';
console.log(str.toUpperCase()); // 输出: 'HELLO'
1
2

  • .toLowerCase():将字符串转为小写
const str = 'HELLO';
console.log(str.toLowerCase()); // 输出: 'hello'
1
2

  • .trim():将字符串去除首尾空格
const str = '  hello  ';
console.log(str.trim()); // 输出: 'hello'
1
2

一般情况下,我们在网页输入用户名,会处理一下,将用户名前后的空格去掉,避免用户误输入。


  • .trimStart():去除字符串前面的空格
const str = '  hello  ';
console.log(str.trimStart()); // 输出: 'hello  '
1
2

  • .trimEnd():去除字符串后面的空格
const str = '  hello  ';
console.log(str.trimEnd()); // 输出: '  hello'
1
2

  • .replace(search, value):替换字符串中第一个匹配的子串
const str = 'hello';
console.log(str.replace('l', 'x')); // 将字符串中第一个l替换为x,输出: 'hexlo'
1
2

  • .replaceAll(search, value):替换字符串中所有匹配的子串
const str = 'hello';
console.log(str.replaceAll('l', 'x')); // 将字符串中所有的l替换为x,输出: 'hexxo'
1
2

# 5 分割与拼接

  • .split(separator):将字符串按分隔符分割为数组
const str = 'a,b,c';
console.log(str.split(',')); // 使用,分隔字符串,输出: ['a', 'b', 'c']
1
2

这个方法和数组的 join() 操作是相反的。


  • .concat(value):拼接字符串,前面讲字符串拼接的时候讲过多种拼接方式。
const str = 'hello';
console.log(str.concat(' world')); // 输出: 'hello world'
1
2

  • .repeat(n):将字符串重复 n 次
const str = 'na';
console.log(str.repeat(3)); // 输出: 'nanana'
1
2

# 6 补全类方法

  • padStart(targetLength, padString) :从开头补全字符串(默认使用空格补全)直到达到指定长度。
const str = '5';
console.log(str.padStart(3, '0')); // 在字符串头部补全0,直到长度为3,输出: '005'
1
2

有时候得到日期,例如1, 2, 10, 23,需要将1和2补0,就可以使用 padStart() 方法。


  • padEnd(targetLength, padString) :从结尾补全字符串(默认使用空格补全)直到达到指定长度。
const str = '5';
console.log(str.padEnd(3, '0')); // 在字符串结尾补全0,直到长度为3,输出: '500'
1
2

# 13.2 正则表达式

什么是正则表达式?

正则表达式(Regular Expression,简称 RegExp)是一种用于匹配字符串中符合特定规则的内容的工具。可以用来查找、替换、验证字符串,比如输入的邮箱格式是否正确。

因为这里是 JavaScript 教程,不是正则表达式的教程,所以这里主要是讲解在 JavaScript 中如何使用正则表达式,关于正则表达式的详细使用,这里就不过多介绍了。

如果你想入门正则表达式,这里推荐一下:正则表达式30分钟入门教程 (opens new window)

下面就介绍一下如何在 JavaScript 中使用正则表达式。


# 1 创建正则表达式

在 JavaScript 中使用正则表达式,首先要创建正则表达式对象。

// 方式1:通过构造函数来创建,第一个参数是正则表达式,第二个参数是匹配模式
let reg1 = new RegExp("aaa", "i");
console.log(reg1);  // 输出:/aaa/i

// 方式2:通过字面量来创建,格式:/正则表达式/匹配模式
let reg2 = /aaa/i;
console.log(reg2);  // 输出:/aaa/i
1
2
3
4
5
6
7
  • 上面两种方式,第一种方式第一个参数是字符串,所以我们可以动态的创建正则表达式,但是有一个问题,因为是字符串,所以就涉及到字符的转义。例如 \ 需要写为 \\
  • 模式有 gimg 为全局匹配,找出所有匹配项,i 表示忽略大小写,m 表示多行匹配模式。默认匹配模式是:非全局(只匹配第一个)、区分大小写、单行模式

可以同时加多个标志:

const regex = /hello/gi;
1

表示:忽略大小写 + 全局匹配giig 是一样的,还可以三种模式都使用。

# 2 正则表达式演示

下面测试一个字符串中是否包含字母 a :

let reg = /a/;   // 创建正则表达式
      
let str1 = 'abc';
let str2 = 'bcd';

console.log(reg.test(str1));   // true
console.log(reg.test(str2));   // false
1
2
3
4
5
6
7
  • 在上面的代码中,test() 表示是否匹配,返回布尔值。

# 3 提取匹配信息

exec() 方法可以返回第一个匹配项的详细信息(数组),如果没有匹配,返回 null

举个例子:

const regex = /(\d+)\s(\w+)/;    // 匹配数字+空格+字母/数字/下划线/汉字
const str = "123 apples and 456 bananas";
let result = regex.exec(str);
console.log(result);
console.log(result[0]);
1
2
3
4
5

输出:

[
  '123 apples',  // 完整匹配
  '123',         // 第1个分组 (\d+)
  'apples',      // 第2个分组 (\w+)
  index: 0,
  input: '123 apples and 456 bananas',
  groups: undefined
]
123 apples
1
2
3
4
5
6
7
8
9
  • 返回的 result 是一个数组,数组的第一个元素是匹配的内容。
  • exec() 支持分组提取,返回结构后面的元素是根据分组匹配的内容。

可以循环使用 exec() 查找多个结果(必须配合 /g 标志,否则多次执行只会读取第一个匹配项)。

举个栗子:

const regex = /(\d+)\s(\w+)/g;   // 匹配数字+空格+字母/数字/下划线/汉字
const str = "123 apples and 456 bananas";
let result = regex.exec(str);

while(result) {
  console.log(result);  
  result = regex.exec(str);  // 再次读取后面的匹配项
}
1
2
3
4
5
6
7
8

执行结果:

['123 apples', '123', 'apples', index: 0, input: '123 apples and 456 bananas', groups: undefined]
['456 bananas', '456', 'bananas', index: 15, input: '123 apples and 456 bananas', groups: undefined]
1
2

# 4 提取多个匹配项

match() 可以以数组的形式返回多个匹配项。

注意,是以字符串来调用,正则表达式作为参数。

举个栗子:

const regex = /(\d+)\s(\w+)/g; // 匹配数字+空格+字母/数字/下划线/汉字
const str = "123 apples and 456 bananas";
let result = str.match(regex);
console.log(result);   // ['123 apples', '456 bananas']
1
2
3
4
  • match() 方法返回结构是所有的匹配项。
  • 注意,正则表达式需要添加 g 模式,否则返回结果和 exec() 方法类似(包含分组信息)。

# 5 替换内容

replace() 方法可以接收正则表达式作为参数,替换正则表达式的匹配项。

举个栗子:

const str = "apple123";
console.log(str.replace(/\d+/, '')); // 将数字替换为'',也就是去掉数字,结果为:"apple"
1
2

还可以使用分组:

const str = "Name: John";
const newStr = str.replace(/Name:\s(\w+)/, 'User: $1');
console.log(newStr); // "User: John"
1
2
3
  • $1 代表第1个括号分组里的内容,$2 第2个(如果有的话),以此类推。

如果 replace() 使用 g 模式,可以进行全局替换,当然你也可以使用 replaceAll() 方法,不过 replaceAll() 只能使用 g 模式,否则会报错。

# 6 拆分字符串

拆分字符串,split() 方法也支持正则表达式。

举个栗子:

const data = "apple, banana; orange  grape";
console.log(data.split(/[\s,;]+/)); // ["apple", "banana", "orange", "grape"]
1
2
  • 上面以空格、逗号、分号拆分字符串。

# 7 查找匹配位置

search() 方法可以返回第一个匹配项在字符串中的索引(位置),找不到返回 -1,和 indexOf() 类似,但是 indexOf() 不能使用正则表达式。

举个栗子:

const str = "Contact: user@example.com";
console.log(str.search(/\w+@\w+\.\w+/)); // 查找邮箱开始的位置,返回:9
1
2
  • 上面正则表达式是匹配邮箱,查找邮箱账号开始的位置。