我需要比较字符串,并且想要测试它们的字符最多不同 a 个元素,例如:
// for a = 2 comparing all strings with str1
var str1 = 'qwerty'; // should return true
var str2 = 'qwerty'; // should return true
var str3 = 'qw1rty'; // should return true
var str4 = '1wery1'; // should return true
var str5 = 'q1e11y'; // should return false
为了完成这个任务,我创建了一个函数,虽然它能够工作,但我想知道是否可以使用正则表达式来实现。我的实际函数如下:
function test(str1, str2, limit) {
const occ = str1.split('').reduce((acc, char, idx) => str2[idx] == char ? ++acc : acc, 0);
return str1.length - occ <= limit;
}
// for a = 2 comparing all strings with str1
var str1 = 'qwerty'; // should return true
var str2 = 'qwerty'; // should return true
var str3 = 'qwert1'; // should return true
var str4 = 'qwer11'; // should return true
var str5 = 'qwe111'; // should return false
console.log(test(str1, str1, 2)) // true
console.log(test(str1, str2, 2)) // true
console.log(test(str1, str3, 2)) // true
console.log(test(str1, str4, 2)) // true
console.log(test(str1, str5, 2)) // false
node
进行服务器端处理,所以javascript
是必需的。 - guijobPython
示例。 - Jan