正則表達式在 JavaScript 中的應用非常廣泛,尤其是在字符串處理和驗證方面。以下是一些常見的正則表達式方法及其應用示例,包括 .test()
方法。
1. .test()
方法
.test()
方法用于測試一個字符串是否匹配正則表達式。如果匹配,返回 true
;否則返回 false
。
示例:
const regex = /hello/;
console.log(regex.test("hello world")); // true
console.log(regex.test("Hi there!")); // false
2. .exec()
方法
.exec()
方法用于在字符串中執行搜索,返回匹配結果的數組或 null
。
示例:
const regex = /quick/;
const result = regex.exec("The quick brown fox");
console.log(result); // ["quick", index: 4, input: "The quick brown fox", groups: undefined]
3. .match()
方法
.match()
方法用于在字符串中查找匹配的正則表達式,并返回一個數組。
示例:
const str = "The quick brown fox jumps over the lazy dog.";
const words = str.match(/\b\w+\b/g);
console.log(words); // ["The", "quick", "brown", "fox", "jumps", "over", "the", "lazy", "dog"]
4. .replace()
方法
.replace()
方法用于替換字符串中匹配正則表達式的部分。
示例:
const str = "The quick brown fox jumps over the lazy dog.";
const newStr = str.replace(/fox/, 'cat');
console.log(newStr); // "The quick brown cat jumps over the lazy dog."
5. .search()
方法
.search()
方法用于查找字符串中匹配正則表達式的索引。如果找到匹配,返回匹配的起始位置;如果沒有找到,返回 -1
。
示例:
const str = "The quick brown fox jumps over the lazy dog.";
const index = str.search(/brown/);
console.log(index); // 10
6. .split()
方法
.split()
方法可以使用正則表達式作為分隔符來分割字符串。
示例:
const str = "apple, banana; orange|grape";
const fruits = str.split(/[,;|]/);
console.log(fruits); // ["apple", " banana", " orange", "grape"]
7. 驗證輸入格式
正則表達式常用于驗證用戶輸入的格式,例如電子郵件、電話號碼等。
驗證電子郵件格式:
function validateEmail(email) {const regex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;return regex.test(email);
}console.log(validateEmail("test@example.com")); // true
console.log(validateEmail("invalid-email")); // false
驗證電話號碼格式:
function validatePhoneNumber(phone) {const regex = /^\d{3}-\d{3}-\d{4}$/; // 格式: 123-456-7890return regex.test(phone);
}console.log(validatePhoneNumber("123-456-7890")); // true
console.log(validatePhoneNumber("1234567890")); // false
總結
正則表達式在 JavaScript 中提供了強大的字符串處理能力。通過使用 .test()
、.exec()
、.match()
、.replace()
、.search()
和 .split()
等方法,開發者可以高效地進行字符串匹配、搜索、替換和驗證。掌握正則表達式的用法可以幫助你在處理文本數據時更加靈活和高效。