JavaScript 中的电话号码正则表达式
每个国家都有自己的数字格式,在我们将这些数据存储到数据库之前,我们需要确保用户输入的数字格式正确。在这篇文章中,我们将学习如何在 JavaScript 中为电话号码编写正则表达式。
JavaScript 中的 RegEx
正则表达式就像一个搜索工具,可以在字符串中找到特定的模式。学习 RegEx 的一个很好的资源是 https://regexr.com。JavaScript 还支持将正则表达式作为对象。这些模式与 matchAll()
、match()
、replaceAll()
、replace()
、search()
和 split()
一起使用。构造正则表达式有两种方式,使用字面量的正则表达式和调用 RegExp 对象的构造函数。
在继续讨论电话号码 RegEx 之前,让我们先了解一些常见模式。
\d
:此正则表达式匹配任何数字/数字。它类似于[0-9]
。\w
:此正则表达式匹配A
-Z
、a
-z
、0
-9
和_
范围内的任何给定单词字符代码。\s
:此正则表达式匹配每个空白字符,例如空格、制表符、换行符。\b
:此正则表达式匹配单词字符和非单词字符之间的任何单词边界位置或位置(字符串的开头/结尾)。[A-Z]
:此正则表达式匹配A
-Z
范围内的任何给定字符代码。[0-9]
:此正则表达式匹配0
-9
范围内的任何给定字符代码。(?:ABC)
:此正则表达式将多个标记组合在一起而不创建捕获组。
每个 RegEx 都包含下面列出的某些标签:
i
:这个标志意味着它不区分大小写,这意味着整个表达式不区分大小写。g
:此标志表示全局搜索,它维护最后一个匹配项的索引,以便后续搜索可以从前一个匹配项的末尾开始。如果没有全局标志,后续搜索将返回相同的匹配项。m
:这个标志表示多行。当多行标志打开时,开始和结束锚点(^
和$
)匹配一行的开头和结尾,而不是整个链的开头和结尾。u
:此标志表示 Unicode。用户可以通过激活此标志来使用\ x {FFFFF}
形式的扩展 Unicode 转义。y
:这个标志意味着粘性。该表达式仅匹配其 lastIndex 位置,并忽略全局标志 (g)(如果已设置)。由于 RegEx 中的每次搜索都是离散的,因此该指标对显示的结果没有进一步的影响。s
:该标志表示 dotAll。句点 (.
) 匹配每个字符,包括新行。
JavaScript 中正则表达式的语法
const regEx = /pattern/;
const regEx = new RegExp('pattern');
示例代码:
<form name="form1">
<input type='text' id="phoneNumber" name='text1'/>
<button type="submit" name="submit" onclick="phonenumber()">Submit</button>
</form>
function phonenumber() {
const indiaRegex = /^\+91\d{10}$/;
const inputText = document.getElementById('phoneNumber').value;
if (inputText.match(indiaRegex)) {
console.log('Valid phone number');
} else {
console.log('Not a valid Phone Number');
}
}
输出:
相关文章
Do you understand JavaScript closures?
发布时间:2025/02/21 浏览次数:108 分类:JavaScript
-
The function of a closure can be inferred from its name, suggesting that it is related to the concept of scope. A closure itself is a core concept in JavaScript, and being a core concept, it is naturally also a difficult one.
Do you know about the hidden traps in variables in JavaScript?
发布时间:2025/02/21 浏览次数:178 分类:JavaScript
-
Whether you're just starting to learn JavaScript or have been using it for a long time, I believe you'll encounter some traps related to JavaScript variable scope. The goal is to identify these traps before you fall into them, in order to av
How much do you know about the Prototype Chain?
发布时间:2025/02/21 浏览次数:150 分类:JavaScript
-
The prototype chain can be considered one of the core features of JavaScript, and certainly one of its more challenging aspects. If you've learned other object-oriented programming languages, you may find it somewhat confusing when you start
用 jQuery 检查复选框是否被选中
发布时间:2024/03/24 浏览次数:102 分类:JavaScript
-
在本教程中学习 jQuery 检查复选框是否被选中的所有很酷的方法。我们展示了使用直接 DOM 操作、提取 JavaScript 属性的 jQuery 方法以及使用 jQuery 选择器的不同方法。你还将找到许多有用的
jQuery 中的 Window.onload 与 $(document).ready
发布时间:2024/03/24 浏览次数:180 分类:JavaScript
-
本教程演示了如何在 jQuery 中使用 Window.onload 和 $(document).ready 事件。