replace(searchValue, replaceValue) は、Javascriptの文字列オブジェクトのメソッドの1つで、文字列の中で指定された検索文字列(searchValue)を置換文字列(replaceValue)に置き換えます。
replace() メソッドは、最初にマッチした検索文字列のみを置換します。もし、すべての検索文字列を置換したい場合は、正規表現を使用する必要があります。
以下に、replace() メソッドの使い方の例を示します。
const string = "I have 3 apples.";
const replacedString = string.replace("3", "5");
console.log(replacedString); // "I have 5 apples."
上記の例では、string の中から数字 “3” を抽出するために、検索文字列として “3” を指定し、置換文字列として “5” を指定しています。そして、replace() メソッドを用いて、string 中の “3” を “5” に置換した文字列 replacedString を作成しています。
また、正規表現を使って複数の検索文字列を置換する場合は、以下のようにします。
const string = "I have 3 apples and 2 bananas.";
const replacedString = string.replace(/\d+/g, "5");
console.log(replacedString); // "I have 5 apples and 5 bananas."
上記の例では、正規表現 /d+/g を使って、string 中の数字をすべて “5” に置換しています。正規表現に g フラグを指定することで、すべてのマッチした文字列を置換することができます。