Is there any way to calculate % match between 2 strings?
有什么方法可以计算两个字符串之间的%匹配吗?
i have a situation where it is required to calculate matches between 2 strings if there is 85%
我有这样一种情况,如果有85%的字符串,就需要计算两个字符串之间的匹配
match then i will combine 2 tables, i have written the code for combining 2 tables
然后我将合并两个表,我已经编写了合并两个表的代码。
my sample strings are :
我的示例字符串是:
var str1 = 'i love javascript';
var str2 = 'i love javascripttt';
var matchPer = match(str1,str2); // result might be 80% , 85%, 90% ,95% etc
1 个解决方案
#1
10
Something like this?
是这样的吗?
var str1 = 'i love javascript';
var str2 = 'i love javascripttt';
function match(str1, str2){
var tmpValue = 0;
var minLength = str1.length;
if(str1.length > str2.length){
var minLength = str2.length;
}
var maxLength = str1.length;
if(str1.length < str2.length){
var maxLength = str2.length;
}
for(var i = 0; i < minLength; i++) {
if(str1[i] == str2[i]) {
tmpValue++;
}
}
var weight = tmpValue / maxLength;
return (weight * 100) + "%";
}
var matchPer = match(str1,str2);
console.log(matchPer); //outputs: 89.47%
console.log( match("aaaaa", "aaaaa") ); //outputs: 100%
console.log( match("aaaaa", "aXaaa") ); //outputs: 80%
console.log( match("aaaaa", "aXXaa") ); //outputs: 60%
console.log( match("aaaaa", "aXXXa") ); //outputs: 40%
console.log( match("aaaaa", "aXXXX") ); //outputs: 20%
#1
10
Something like this?
是这样的吗?
var str1 = 'i love javascript';
var str2 = 'i love javascripttt';
function match(str1, str2){
var tmpValue = 0;
var minLength = str1.length;
if(str1.length > str2.length){
var minLength = str2.length;
}
var maxLength = str1.length;
if(str1.length < str2.length){
var maxLength = str2.length;
}
for(var i = 0; i < minLength; i++) {
if(str1[i] == str2[i]) {
tmpValue++;
}
}
var weight = tmpValue / maxLength;
return (weight * 100) + "%";
}
var matchPer = match(str1,str2);
console.log(matchPer); //outputs: 89.47%
console.log( match("aaaaa", "aaaaa") ); //outputs: 100%
console.log( match("aaaaa", "aXaaa") ); //outputs: 80%
console.log( match("aaaaa", "aXXaa") ); //outputs: 60%
console.log( match("aaaaa", "aXXXa") ); //outputs: 40%
console.log( match("aaaaa", "aXXXX") ); //outputs: 20%