Skip to content
Advertisement

How to check if at least three letters from both variables match

let nameOne = 'christian|';
let nameTwo = 'christiana';

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):

function haveSameNCharacters (length, str1, str2) {
  const [shorter, longer] = [str1, str2].sort(({length: a}, {length: b}) => a - b);
  if (length > shorter.length) throw new Error('Invalid length');
  if (length === shorter.length) return longer.includes(shorter);

  for (let i = 0; i <= shorter.length - length; i += 1) {
    const substr = shorter.slice(i, i + length);
    if (longer.includes(substr)) return true;
  }

  return false;
}

const result = haveSameNCharacters(3, 'christian|', 'christiana');
console.log(result);

console.log(haveSameNCharacters(3, 'flagpole', 'poland'));
console.log(haveSameNCharacters(3, 'yellow', 'orange'));
console.log(haveSameNCharacters(3, 'mountain', 'untie'));
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement