[英]Javascript search not working as expected. How to resolve?
I am trying to execute search but it not working as per my expectation. 我正在尝试执行搜索,但是按我的期望它不起作用。 It returning 0 instead 2. How to resolve it?
它返回0而不是2。如何解决?
var number = '4,4'; alert(number.search(/4/g));
.search
returns the index of the match. .search
返回匹配的索引 。 4
is matched at index 0 of the string, so it returns 0. If you wanted to check how many times 4 occurs in the string, use .match
instead, and check the .length
of the match object: 4
在字符串的索引0处匹配,因此返回0。如果要检查字符串中出现4的次数,请改用.match
并检查match对象的.length
:
var number = '4,4'; const match = number.match(/4/g); console.log((match || []).length);
(the || []
is needed in case match
is null, in which case you'd want 0, rather than a thrown error) (如果
match
为null,则需要|| []
,在这种情况下,您希望的是0,而不是抛出错误)
I think you mean to count the number of occurrences. 我认为您的意思是计算发生次数。
Use regex to store the occurrences and return the length to indicate the count. 使用正则表达式存储事件并返回长度以指示计数。
var temp = "4,4"; var count = (temp.match(/4/g) || []).length; console.log(count);
The search() method searches a string for a specified value, and returns the position of the match. search()方法在字符串中搜索指定的值,然后返回匹配的位置。 if you what to count the occurrences you must to make something like this:
如果您要计算发生次数,则必须进行如下操作:
var number = '4,4'; var qtd = (number.match(/4/g) || []).length; alert(qtd);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.