skip to Main Content

I am looking for the easiest way to find the longest common suffix of two strings in JavaScript.

I found a question about longest common prefix but nothing for suffix.

3

Answers


  1. Chosen as BEST ANSWER
    const commonSuffix = (str1: string, str2: string) => {
        for (let i1 = str1.length - 1, i2 = str2.length - 1; i1 >= 0 && i2 >= 0; i1--, i2--) {
            if (str1[i1] !== str2[i2]) {
                return str1.substr(i1 + 1);
            }
        }
        return str1.length < str2.length ? str1 : str2;
    };
    

  2. For fun, I am providing an alternate solution which first transforms the strings into arrays then finds the common suffix.

    let a = '123567';
    let b = '124567';
    
    function commonSuffix(a, b) {
      let arrayA = [...a].reverse(), arrayB = [...b].reverse();
                    
      let match = [];
      arrayA.every((item, i) => arrayB[i] === item && match.unshift(item));
      return match.join('');
    }
    
    console.log(commonSuffix(a, b));
    Login or Signup to reply.
  3. You can use this:

    function longestCommonSuffix(str1, str2) {
        let i = 0;
        while (i < str1.length && i < str2.length && str1[str1.length - 1 - i] === str2[str2.length - 1 - i]) {
            i++;
        }
        return str1.slice(str1.length - i);
    }
    
    // Example usage:
    console.log(longestCommonSuffix("programming", "coding")); // Outputs: "ing"
    console.log(longestCommonSuffix("hello", "world"));       // Outputs: ""
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search