replace 方法的参数
String.prototype.replace
方法用于替换字符串中的匹配内容。它可以接收两个参数:
-
第一个参数:匹配模式
- 可以是一个字符串:直接匹配该字符串。
- 可以是一个正则表达式:匹配符合正则表达式的内容。
-
第二个参数:替换内容
- 可以是一个字符串:用于替换匹配到的内容。
- 可以是一个回调函数:动态生成替换内容。
示例
javascript
// 使用字符串作为匹配模式
console.log('hello world'.replace('world', 'JavaScript'));
// 输出: "hello JavaScript"
// 使用正则表达式作为匹配模式
console.log('hello world'.replace(/world/, 'JavaScript'));
// 输出: "hello JavaScript"
// 使用回调函数作为替换内容
console.log('hello world'.replace(/(world)/, (match) => match.toUpperCase()));
// 输出: "hello WORLD"
replace 回调函数的参数
当 replace 的第二个参数是回调函数时,回调函数会接收以下参数:
- match:匹配到的子字符串。
p1, p2, ...
:正则表达式中的捕获组(如果有)。offset
:匹配到的子字符串在原字符串中的索引。string
:被匹配的原字符串。
示例
typescript
const str = 'color: red; backgroundColor: blue;';
const result = str.replace(/([A-Z])/g, (match, p1, offset, string) => {
console.log(`Match: ${match}, Captured: ${p1}, Offset: ${offset}, String: ${string}`);
return `-${p1.toLowerCase()}`;
});
console.log(result);
// 输出:
// Match: C, Captured: C, Offset: 13, String: color: red; backgroundColor: blue;
// color: red; background-color: blue;
正则校验的几个方法
正则表达式在 JavaScript 中有多种方法可以用来匹配和操作字符串:
-
- 用于测试字符串是否匹配正则表达式。
- 返回布尔值。
javascript
const regex = /hello/;
console.log(regex.test('hello world')); // true
-
exec
- 用于匹配字符串,返回第一个匹配结果的详细信息(数组形式)。
- 如果没有匹配到,返回
null
。
javascript
const regex = /hello/;
console.log(regex.exec('hello world'));
// ["hello", index: 0, input: "hello world"]
-
- 用于从字符串中提取匹配结果。
- 返回一个数组,包含所有匹配的内容。
python
const str = 'hello world';
console.log(str.match(/hello/)); // ["hello", index: 0, input: "hello world"]
-
- 用于替换匹配的内容。
- 返回替换后的新字符串。
javascript
const str = 'hello world';
console.log(str.replace(/world/, 'JavaScript')); // "hello JavaScript"
-
split
- 用于根据正则表达式分割字符串。
- 返回一个数组。
javascript
const str = 'hello world';
console.log(str.split(/\s/)); // ["hello", "world"]