TypeScript - 字串 replace() 方法



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

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

模式 插入
$$ 插入一個“$”。
$& 插入匹配的子字串。
$` 插入匹配子字串之前的字串部分。
$' 插入匹配子字串之後的字串部分。
$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)

編譯後,它將在 JavaScript 中生成相同的程式碼。

其輸出如下:

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);

編譯後,它將在 JavaScript 中生成相同的程式碼。

其輸出如下:

ali, zara
typescript_strings.htm
廣告
© . All rights reserved.