-4

I have a string like this : 33,33,56,89,56

I need to find out how to calculate the number of similar strings parts in that string using both JavaScript?

like for 33,33,56,89,56 how many '33's and how many 56s are there? using JavaScript? The split or match wont work here. actually the scenario is: There are several buttons having the same class and one custom attribute price here for product rows. Now on click event i am fetching the value like this $('.product_row').attr('price'); , now i need to calculate what product is being clicked here and how many times? and i need to calculate if it is a similar product being clicked , how many times it is being clicked?

So, it 33,33,56,89,56 this string will be generated dynamically.

Help here guys.

shams
  • 124
  • 10

3 Answers3

1

I'm not sure about javascript, but here is PHP:

$data = "33,33,56,89,56";    
$dataAsArray = explode(",", $data);
$valueCount = array_count_values($dataAsArray);
echo $valueCount[56]; // Should output 2

Edit: As for JavaScript, have a look here: array_count_values for JavaScript instead

Community
  • 1
  • 1
eXaminator
  • 353
  • 1
  • 8
0

For PHP, see http://php.net/manual/en/function.substr-count.php

<?php
$text = 'This is a test';
echo strlen($text); // 14

echo substr_count($text, 'is'); // 2

// the string is reduced to 's is a test', so it prints 1
echo substr_count($text, 'is', 3);

// the text is reduced to 's i', so it prints 0
echo substr_count($text, 'is', 3, 3);

// generates a warning because 5+10 > 14
echo substr_count($text, 'is', 5, 10);


// prints only 1, because it doesn't count overlapped substrings
$text2 = 'gcdgcdgcd';
echo substr_count($text2, 'gcdgcd');
?>

JS:

var foo = 'This is a test';
var count = foo.match(/is/g);
console.log(count.length);
Harri
  • 2,692
  • 2
  • 21
  • 25
0

Try it

<?php 
$str = "33,33,56,89,56,56";
echo substr_count($str, '56');
?>

<script type="text/javascript">
var temp = "33,33,56,89,56,56";
var count = temp.match(/56/g);  
alert(count.length);
</script>