replaceAll() 方法用于替换字符串中的所有匹配项。它与replace() 方法类似,但是它替换字符串中的所有匹配项,而不是第一个匹配项。
replaceAll() 方法接受两个参数:要替换的字符串(正则表达式)和要替换为的字符串。
下面是一个使用replaceAll() 方法的示例:
let str = "Hello World, Hello World!"; let newStr = str.replaceAll("Hello", "Goodbye"); console.log(newStr); // Goodbye World, Goodbye World!
在上面的示例中,我们声明了一个字符串变量,使用replaceAll() 方法替换了字符串中所有的“Hello”字符串,替换为“Goodbye”字符串。我们使用了console.log() 方法来输出结果。
replaceAll() 方法也可以用来替换正则表达式:
let str = "Hello World, Hello World!"; let newStr = str.replaceAll(/Hello/g, "Goodbye"); console.log(newStr); // Goodbye World, Goodbye World!
在上面的示例中,我们使用了正则表达式来替换字符串中所有的“Hello”字符串,替换为“Goodbye”字符串。
replaceAll() 方法对于替换字符串中的所有匹配项非常有用,它可以节省大量的时间,而不必一个一个地替换。