Typescript-string-replace
提供:Dev Guides
TypeScript-ストリングreplace()
このメソッドは、正規表現と文字列の一致を検出し、一致した部分文字列を新しい部分文字列で置き換えます。
置換文字列には、次の特別な置換パターンを含めることができます-
Pattern | Inserts |
---|---|
DOLLARDOLLAR | Inserts a "DOLLAR". |
DOLLAR& | Inserts the matched substring. |
DOLLAR` | Inserts the portion of the string that precedes the matched substring. |
DOLLAR' | Inserts the portion of the string that follows the matched substring. |
DOLLARn or DOLLARnn | Where n *or nn* are decimal digits, inserts the nth parenthesized submatch string, provided the first argument was a RegExp object. |
構文
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