怎么找不。 javascript中两个字符串中的相似字符[关闭]

I need to find the no. of similar characters between two strings using JS/PHP

Example str1: Mack str2: Michelle

Similar Characters: "M" "C" similar character count: 2

After your precision, here is my solution:

str1 = str1.toUpperCase();
str2 = str2.toUpperCase();
var counter = 0, find = -1;
for(var i = 0; i < str1.length; i++)
{
    find = str2.indexOf(str1.charAt(i));
    if(find > -1)
    {
      counter++;
      str2 = str2.substr(0, find) + str2.substr(find + 1);
    }
}
alert("Result: "+counter);

It works with the 2 examples you gave us:

Michellle and Michelle = 8 Sneha and naveen = 3

I'll do this:

str1 = str1.toUpperCase();
str2 = str2.toUpperCase();
var counter = 0;
var min = Math.min(str1.length, str2.length);
for(var i = 0; i < min; i++)
{
   if(str1.charAt(i) === star2.charAt(i))
      counter++;
}
alert("Result: "+counter);

Use similar_text() function

<?php
    echo "character count: ". similar_text("Mack","Michelle");
?>

Output

character count: 2

I'd need more examples to make sure this works, but using regular expressions might work for you:

function similar_text_regex(str1, str2){
    var regEx = new RegExp('['+str2+']', 'gi');
    var matchCnt = str1.match(regEx2).length;
    return matchCnt;
}

console.log(similar_text_regex('Michelle', 'Michellle')); // --> 8
console.log(similar_text_regex('Jason', 'Jane')); // --> 3
console.log(similar_text_regex("sneha","naveen")); // --> 3