开发学院

您的位置:首页>教程>正文

教程正文

ES6 String对象方法replace()

ES6 String对象方法replace()

  replace()方法用于在字符串中用一些字符替换另一些字符,或替换一个与正则表达式匹配的子串。

  替换字符串可以包括以下特殊的替换模式

  • $$:插入一个"$".

  • $&:插入匹配的子字符串.

  • $`:插入匹配子字符串之前的字符串的一部分。

  • $':插入匹配匹配子字符串的字符串的一部分。

  • $n或$nn:其中n或nn是十进制数字,插入第n个带括号的submatch字符串,前提是第一个参数是正则表达式对象。

语法

string.replace(regexp/substr, newSubStr/function[, flags]);

参数详情

  • regexp − 正则表达式对象。匹配到的值由参数#2替换。

  • substr − 将由newsubstr替换的字符串。

  • function − 要调用以创建新子字符串的函数。

  • flags −包含正则表达式标记的任何组合的字符串: g

返回值

  返回一个新的替换后字符串。

例子

var re = /apples/gi; 
var str = "Apples are round, and apples are juicy."; 
var newstr = str.replace(re, "oranges"); 
console.log(newstr)

输出

oranges are round, and oranges are juicy.

例子

var re = /(\w+)\s(\w+)/; 
var str = "zara ali"; 
var newstr = str.replace(re, "$2, $1"); 
console.log(newstr);

输出

ali, zara