使用 JavaScript 计算字符串中的出现次数
我们将使用 JavaScript 匹配方法来计算字符串中特定单词/字符的总出现次数。但在我们了解这一点之前,让我们先了解一下什么是正则表达式。
正则表达式是一种可以实现特定字符串模式的搜索。JavaScript 还支持将正则表达式作为对象。
这些模式与 split()
、replace()
、search()
、match()
、matchAll()
和 replaceAll()
一起使用。
构造正则表达式有两种方法,使用文字正则表达式或调用 RegEx 的构造函数。
有关 RegEx 的更多信息,请参见 RegEx
的文档。
在继续计算匹配字符串的出现次数之前,让我们了解一些常见的模式。
每个 RegEx 都包含某些标志。每个标志都有其含义,它为正则表达式提供了额外的属性。
下面列出了其中一些:
语法:
const regEx = /pattern/;
const regEx = new RegExp('pattern');
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");
}
}
match()
方法是一个内置的 JavaScript 方法。此方法检索将字符串/字符与原始字符串提供的正则表达式进行匹配的结果。
语法:
match(regexp)
它将正则表达式作为输入参数,并根据原始字符串查找匹配的字符串/字符。
它是一个可选参数。如果在 match 方法中没有将正则表达式作为参数传递,它将返回带有空字符串的数组。
根据正则表达式的 g
(全局)标志,它返回数组。如果通过了 g
标志,则返回所有匹配的字符串/字符。
有关详细信息,请参阅 match
方法文档。
var inputString = "Hello World. This is a string.";
var count = (inputString.match(/is/g) || []).length;
console.log(count);
在上面的代码中,我们试图确定 is
这个词的总出现次数,而不管它在哪里。
如果你传递 g
(全局)标志,它将尝试找出所有匹配项。例如,This
中的 is
是有效匹配。
一旦你在任何浏览器中运行上述代码,它就会打印出类似这样的内容。
输出:
2
相关文章
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 事件。