简体   繁体   English

Javascript搜索无法正常工作。 怎么解决?

[英]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.

相关问题 Javascript“ for..of”无法正常工作。 - Javascript “for..of” not working as expected. Javascript 全局变量未按预期工作。 帮助? - Javascript Global Variables Not Working as expected. Help? PopState无法正常工作。 - PopState not working as expected. 角度组件中的模板无法正常工作。 - Template in angular component not working as expected. javascript 推送 function 未按预期工作。 我正在尝试将数据推送到数组或列表 - javascript push function is not working as expected. I am trying to push data to array or list 我随机生成的图块集无法正常工作。 我怎样才能解决这个问题? - My random generation of a tile set isn't working as expected. How can I fix this? 如何解决错误:从JSON读取器读取时,发现意外的'StartArray'节点。 预期会出现“ StartObject”节点。 - How to resolve error: An unexpected 'StartArray' node was found when reading from the JSON reader. A 'StartObject' node was expected.? JavaScript行为不符合预期。 无法确定原因。 - Javascript not behaving as expected. Unable to identify cause. Firebase orderByKey()。startAt()无法按预期工作。 怎么了? - Firebase orderByKey().startAt() not working as expected. What's wrong? 使用坐标将点绘制到画布上,但未按预期工作。 P5js - Drawing points to canvas with cordinates, not working as expected. P5js
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM