Home > OS >  regex find first similar chars between two different values
regex find first similar chars between two different values

Time:04-11

I have two different values which are completely different from one another, however, the first few chars are similar.

How can I find if the first few chars match between two and if they do, then what they are?

value to match from: rs_list_fame

match against: rs_list_defame return value rs_list

match against: rs_meta return value rs

match against: meta_list return value false

CodePudding user response:

Here's a function that returns the common start of 2 strings.
Without the common trailing underscore.

function common_start_substring (str1, str2) {
  let len = Math.min(str1.length, str2.length);
  let i = 0;
  while(i < len && str1.charAt(i) === str2.charAt(i)) i  ;
  let result = str1.substring(0,i).replace(/_ $/,'');
  return result.length > 0 ? result : false;
}

let str = 'rs_list_fame';
let arr = ['rs_list_defame', 'rs_meta', 'meta_list'];

arr.forEach(s => console.log(s ' --> ' common_start_substring(str, s)));

  • Related