0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

JavaScriptのreplaceに気をつけろ!

Posted at

はじめに

同じ名前の関数でも、言語によって機能が異なることがあります。
JavaScriptのreplaceは注意しなければいけないもののひとつです。

言語 メソッド名 動作
C# Replace() すべての一致を置換
Python replace() すべての一致を置換
Java replace() すべての一致を置換
JavaScript replace() 最初の一致だけを置換

各言語の例

C#

string str = "2024/11/14";
string result = str.Replace("/", "-");
Console.WriteLine(result);  // "2024-11-14" (すべてのスラッシュを置換)

Python

str = "2024/11/14"
result = str.replace("/", "-")
print(result)  // "2024-11-14" (すべてのスラッシュを置換)

Java

public class Main {
    public static void main(String[] args) {
        String str = "2024/11/14";
        String result = str.replace("/", "-");
        System.out.println(result);  // "2024-11-14" (すべてのスラッシュを置換)
    }
}

JavaScript

let str = "2024/11/14";
let result = str.replace("/", "-");
console.log(result);  // "2024-11/14" (最初の1箇所だけ置換)

result = str.replace(/\//g, "-");
console.log(result);  // "2024-11-14" (すべてのスラッシュを置換)

最初の1箇所だけなことに注意!!
全てを置換したい場合は正規表現を利用します。
新しめの環境ではreplaceAllでも一気に全部置換できます。

まとめ

  • JavaScript最初の一致のみを置換し、正規表現を使うことで全ての一致を置換可能。
  • C#, Python, Java では replace メソッドがデフォルトで すべての一致を置換し、特別なフラグや設定は不要。

気を付けましょう!!

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?