Rushabh Shah
Rushabh Shah

Reputation: 133

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

Upvotes: 0

Views: 59

Answers (3)

Maikon Matheus
Maikon Matheus

Reputation: 789

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

Upvotes: 0

Danyal Imran
Danyal Imran

Reputation: 2605

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

Upvotes: 0

CertainPerformance
CertainPerformance

Reputation: 370599

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

Upvotes: 1

Related Questions