ES6 - replace() 方法



此方法查詢正則表示式和字串之間的匹配項,並將匹配的子字串替換為新的子字串。

替換字串可以包含以下特殊替換模式:

序號 模式與插入
1

$$

插入一個“$”。

2

$&

插入匹配的子字串。

3

$`

插入匹配的子字串之前的那部分字串。

4

$'

插入匹配的子字串之後的那部分字串。

5

$n 或 $nn

其中nnn 是十進位制數字,插入第 n 個帶括號的子匹配字串,前提是第一個引數是 RegExp 物件。

語法

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

引數詳情

  • regexp - RegExp 物件。匹配項將被引數 #2 的返回值替換。

  • substr - 要被 newSubStr 替換的字串。

  • newSubStr - 替換從引數 #1 收到的子字串的字串。

  • function - 要呼叫以建立新子字串的函式。

  • flags - 包含 RegExp 標誌(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
廣告

© . All rights reserved.