正则表达式(Regular Expression)是一种强大的文本处理工具,可以用于检索、替换、匹配和验证符合特定模式的字符串。在JavaScript中,正则表达式通常用于字符串的方法中,如match()
、replace()
、search()
和split()
等。
以下是一些JavaScript中正则表达式的例子:
const emailRegex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
const email = "example@example.com";
console.log(emailRegex.test(email)); // 输出:true
const phoneRegex = /^1[3-9]\d{9}$/;
const phone = "13800138000";
console.log(phoneRegex.test(phone)); // 输出:true
const str = "Hello World! How are you?";
const newStr = str.replace(/\s+/g, " ");
console.log(newStr); // 输出:"Hello World! How are you?"
const urlRegex = /^(https?:\/\/)?([\da-z.-]+)\.([a-z.]{2,6})([/\w .-]*)*\/?$/;
const url = "https://www.example.com";
console.log(urlRegex.test(url)); // 输出:true
const str = "The price is $100.50";
const numbers = str.match(/\d+(\.\d+)?/g);
console.log(numbers); // 输出:["100", "50"]
/pattern/flags
。RegExp
构造函数创建正则表达式,如new RegExp("pattern", "flags")
。领取专属 10元无门槛券
手把手带您无忧上云