正则表达式(Regular Expression)是一种强大的文本处理工具,它使用单个字符串来描述、匹配一系列符合某个句法规则的字符串。在JavaScript中,正则表达式通常用于字符串的模式匹配、检索和替换。
/pattern/flags
new RegExp('pattern', 'flags')
其中,pattern
是要匹配的正则表达式,flags
是可选的标志,如 g
(全局搜索)、i
(忽略大小写)、m
(多行搜索)等。
以下是一些常用的JavaScript正则表达式示例:
const emailRegex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
console.log(emailRegex.test('example@example.com')); // true
const phoneRegex = /^1[3-9]\d{9}$/;
console.log(phoneRegex.test('13800138000')); // true
const url = 'https://www.example.com/path?query=string';
const domainRegex = /^(?:https?:\/\/)?([^\/]+)/;
const match = url.match(domainRegex);
if (match) {
console.log(match[1]); // 输出:www.example.com
}
const text = '这是一个包含敏感词的文本';
const sensitiveWord = '敏感词';
const replacement = '***';
const regex = new RegExp(sensitiveWord, 'g');
const result = text.replace(regex, replacement);
console.log(result); // 输出:这是一个包含***的文本