JavaScript
x
3
1
let nameOne = 'christian|';
2
let nameTwo = 'christiana';
3
Using JavaScript, how do I check if at least three letters from both variables match?
Advertisement
Answer
If you mean that you want to determine if a contiguous sequence of at least n
(bytes of) characters match in two strings, you could do it like this (sliding window Google query):
JavaScript
1
19
19
1
function haveSameNCharacters (length, str1, str2) {
2
const [shorter, longer] = [str1, str2].sort(({length: a}, {length: b}) => a - b);
3
if (length > shorter.length) throw new Error('Invalid length');
4
if (length === shorter.length) return longer.includes(shorter);
5
6
for (let i = 0; i <= shorter.length - length; i += 1) {
7
const substr = shorter.slice(i, i + length);
8
if (longer.includes(substr)) return true;
9
}
10
11
return false;
12
}
13
14
const result = haveSameNCharacters(3, 'christian|', 'christiana');
15
console.log(result);
16
17
console.log(haveSameNCharacters(3, 'flagpole', 'poland'));
18
console.log(haveSameNCharacters(3, 'yellow', 'orange'));
19
console.log(haveSameNCharacters(3, 'mountain', 'untie'));