JavaScript 字符串替换
字符串替换是日常编程中的常见需求,无论是处理用户输入、格式化显示内容,还是数据清洗,都会用到字符串替换功能。JavaScript提供了多种方法来实现字符串替换,本文将详细介绍这些方法及其适用场景。
基本字符串替换方法
1. replace() 方法
replace()
方法是JavaScript中最基本的字符串替换方法,它返回一个新字符串,并不会修改原字符串。
基本语法
string.replace(searchValue, replaceValue)
参数解释:
searchValue
:被替换的字符串或正则表达式replaceValue
:用来替换的字符串或函数
让我们通过几个例子来了解这个方法:
// 基本替换
const str = "Hello World";
const newStr = str.replace("World", "JavaScript");
console.log(newStr); // 输出: Hello JavaScript
console.log(str); // 输出: Hello World (原字符串不变)
// 只替换第一次出现的匹配项
const repeatStr = "apple apple apple";
const result = repeatStr.replace("apple", "orange");
console.log(result); // 输出: orange apple apple
备注
使用字符串作为第一个参数时,replace()
方法仅替换第一个匹配项。
2. 使用正则表达式进行替换
如果要替换字符串中的所有匹配项,可以使用正则表达式和全局标志 g
:
const repeatStr = "apple apple apple";
const result = repeatStr.replace(/apple/g, "orange");
console.log(result); // 输出: orange orange orange
使用正则表达式还可以实现更复杂的替换:
// 忽略大小写替换
const text = "JavaScript is awesome. JAVASCRIPT is fun.";
const caseInsensitive = text.replace(/javascript/gi, "JS");
console.log(caseInsensitive); // 输出: JS is awesome. JS is fun.
// 使用正则捕获组
const name = "Smith, John";
const swapped = name.replace(/(\w+), (\w+)/, "$2 $1");
console.log(swapped); // 输出: John Smith