JavaScriptで文字列が正規表現に一致するかどうかを確認する方法
JavaScriptで文字列が正規表現に一致するかどうかを確認する方法
test() メソッド
test()
メソッドは、文字列が正規表現パターンに一致するかどうかを 真偽値 で返します。
const str = "Hello, world!";
const regex = /world/;
const isMatch = regex.test(str);
console.log(isMatch); // true
この例では、str
変数に "Hello, world!" という文字列、regex
変数に world
という正規表現パターンを割り当てています。test()
メソッドは、regex
パターンが str
文字列に一致するかどうかをチェックし、一致する場合は true
、一致しない場合は false
を返します。
match() メソッド
const str = "Hello, world!";
const regex = /world/;
const matches = str.match(regex);
console.log(matches); // ["world"]
この例では、match()
メソッドは str
文字列が regex
パターンに一致する部分文字列を配列として返します。一致する部分文字列が複数ある場合は、配列に複数の要素が含まれます。
その他のメソッド
test()
メソッドと match()
メソッド以外にも、文字列と正規表現を比較する方法はいくつかあります。
search()
メソッド: 最初の一致部分のインデックスを返します。replace()
メソッド: 一致部分文字列を置換します。
JavaScriptで文字列が正規表現に一致するかどうかを確認するには、test()
メソッド、match()
メソッドなどの方法があります。それぞれのメソッドの特徴を理解して、目的に合った方法を選択してください。
test() メソッド
// メールアドレスの検証
function validateEmail(email) {
const regex = /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return regex.test(email);
}
const email = "[email protected]";
const isValid = validateEmail(email);
console.log(isValid); // true
match() メソッド
// 文字列から数字を抽出
function extractNumbers(str) {
const regex = /\d+/g;
return str.match(regex);
}
const str = "This is a string with 123 numbers 456 and 789.";
const numbers = extractNumbers(str);
console.log(numbers); // ["123", "456", "789"]
この例では、extractNumbers()
関数は、引数として渡された文字列から数字を抽出します。match()
メソッドは、regex
パターンに一致する部分文字列を配列として返します。
その他のメソッド
search()
メソッド
const str = "Hello, world!";
const regex = /world/;
const index = str.search(regex);
console.log(index); // 7
この例では、search()
メソッドは str
文字列の中で regex
パターンに最初に一致する部分文字列のインデックスを返します。
const str = "Hello, world!";
const regex = /world/;
const newStr = str.replace(regex, "Universe");
console.log(newStr); // "Hello, Universe!"
const str = "Hello, world!";
const regex = / /;
const parts = str.split(regex);
console.log(parts); // ["Hello", "world!"]
この例では、split()
メソッドは str
文字列を regex
パターンで分割します。
JavaScriptで文字列が正規表現に一致するかどうかを確認する他の方法
exec() メソッド
const str = "Hello, world!";
const regex = /world/;
const match = regex.exec(str);
console.log(match); // {0: "world", index: 7, input: "Hello, world!"}
exec()
メソッドは、match
オブジェクトに以下のプロパティが含まれます。
0
: 一致した部分文字列index
: 一致した部分文字列の開始インデックスinput
: 検査対象の文字列
ループ
正規表現パターンをループ処理して、文字列が一致するかどうかを確認することもできます。
const str = "Hello, world!";
const regex = /w/g;
let isMatch = false;
for (const match of str.matchAll(regex)) {
isMatch = true;
break;
}
console.log(isMatch); // true
テンプレートリテラルを使って、正規表現パターンを直接文字列に埋め込むこともできます。
const str = "Hello, world!";
const regex = /world/;
const result = `${str.replace(regex, "Universe")}`;
console.log(result); // "Hello, Universe!"
javascript regex match