PHP前端开发

js中replaceall()方法的用法

百变鹏仔 2天前 #JavaScript
文章标签 方法
replaceall() 方法用于在字符串中替换所有匹配指定模式的子字符串,其用法如下:参数 regexp 指定要匹配的正则表达式。参数 replacement 指定用于替换匹配项的字符串。该方法会修改原始字符串。正则表达式中的特殊字符必须转义。如果正则表达式使用全局标志(g),则会替换所有匹配项。如果 replacement 参数为 undefined,则匹配的子字符串将被删除。

replaceAll() 方法的用法

replaceAll() 方法用于在字符串中替换所有匹配指定模式的子字符串。

语法:

string.replaceAll(regexp, replacement)

参数:

返回值:

替换后的新字符串。

用法:

  1. 使用正则表达式匹配:

    let str = "Hello, world!";let newStr = str.replaceAll(/world/, "JavaScript");// newStr = "Hello, JavaScript!"
  2. 使用字符串匹配:

    let str = "JavaScript is fun!";let newStr = str.replaceAll("JavaScript", "Python");// newStr = "Python is fun!"
  3. 使用函数作为替换项:

    let str = "The quick brown fox jumps over the lazy dog";let newStr = str.replaceAll(/the/g, (match) => match.toUpperCase());// newStr = "The QUIck brown fox jumps over the lazy dog"

注意事项:

例子:

// 替换所有数字为 "X"let str = "1234567890";let newStr = str.replaceAll(/[0-9]/g, "X");// newStr = "XXXXXXXXXX"// 替换所有元音为大写let str = "Hello, world!";let newStr = str.replaceAll(/[aeiou]/gi, (match) => match.toUpperCase());// newStr = "H3LL0, w0RLD!"