JavaScriptで文字列を比較し、可能性のパーセンテージを返します
2つの文字列を比較し、それらがどれだけ類似しているかのパーセンテージの可能性を返すことができるJavaScript関数を作成する必要があります。パーセンテージは、2つの文字列に共通する多くの文字の尺度に他なりません。
それらが完全に類似している場合、出力は100であり、共通の文字がまったく含まれていない場合、出力は0である必要があります。
例
const calculateSimilarity = (str1 = '', str2 = '') => {
let longer = str1;
let shorter = str2;
if (str1.length < str2.length) {
longer = str2; shorter = str1;
}
let longerLength = longer.length;
if (longerLength == 0) {
return 1.0;
}
return +((longerLength - matchDestructively(longer, shorter)) / parseFloat(longerLength) * 100).toFixed(2);
};
const matchDestructively = (str1 = '', str2 = '') => {
str1 = str1.toLowerCase();
str2 = str2.toLowerCase();
let arr = new Array();
for (let i = 0; i <= str1.length; i++) {
let lastValue = i;
for (let j = 0; j <= str2.length; j++) {
if (i == 0){
arr[j] = j;
}else if(j > 0){
let newValue = arr[j - 1];
if(str1.charAt(i - 1) != str2.charAt(j - 1))
newValue = Math.min(Math.min(newValue, lastValue), arr[j]) + 1;
arr[j - 1] = lastValue; lastValue = newValue;
}
}
if (i > 0) arr[str2.length] = lastValue;
}
return arr[str2.length];
};
console.log(calculateSimilarity('Mathematics','Mathamatecs')); 出力
これにより、次の出力が生成されます-
[ [ 1, 10, 100 ], [ 1, 10, 200 ], [ 1, 10, 300 ], [ 1, 20, 100 ], [ 1, 20, 200 ], [ 1, 20, 300 ], [ 2, 10, 100 ], [ 2, 10, 200 ], [ 2, 10, 300 ], [ 2, 20, 100 ], [ 2, 20, 200 ], [ 2, 20, 300 ] ]
-
現在のロケールの2つの文字列をJavaScriptと比較するにはどうすればよいですか?
現在のロケールで2つの文字列を比較するには、localeCompare()メソッドを使用します。文字列が等しい場合は0を返し、string1がstring2の前にソートされている場合は-1を返し、string1がstring2の前にソートされている場合は1を返します。 例 次のコードを実行して、JavaScriptで現在のロケールの2つの文字列を比較する方法を学ぶことができます- <!DOCTYPE html> <html> <body> <script> &n
-
JavaScriptのテンプレート文字列。
ES6でテンプレートが導入され、文字列内に式を埋め込むことができるようになりました。 ‘’または“”引用符の代わりに、バッククォート( ``)を使用します。これらは文字列補間のはるかに優れた方法を提供し、式は$ {a+b}のような方法で埋め込むことができます。 +演算子よりもはるかに優れた構文を提供します。 以下はJavaScriptのテンプレート文字列のコードです- 例 <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> &l