简体   繁体   中英

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?

 var number = '4,4'; alert(number.search(/4/g)); 

.search returns the index of the match. 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:

 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)

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. 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); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM