Matteo Pietro Peru
Matteo Pietro Peru

Reputation: 576

Compare two strings and return values that are not present in both

I need (in JavaScript, maybe using RegEx? or some React component) to compare two strings and bold all the words/chars are not present in the "source" string.

For example:

"business plan" compared with "business plafond", should return "business plafond"

"business plan" comprared with "plan and monitoring" should return "plan and monitoring"

Currently I use this method which works but unfortunately not in all cases, I can't find the issue:

compareStrings(a, b) {
let i = 0;
let j = 0;
let result = "";

while (j < b.length)
{
    if (a[i] === ' ') {
        i++;
    } else {
        if ((a[i] != b[j]) || (b[j] === ' ') || i == a.length)
            result += b[j];
        else i++;
        // }
    }

    j++;
}
        return result;
    }

Anyone could help me please?

Upvotes: 2

Views: 1764

Answers (2)

SparkFountain
SparkFountain

Reputation: 2270

From your example, I would suggest the following string comparison strategy:

  • Consider having to strings a and b
  • Take b character by character and find its first occurrence in a
  • If there is a mismatch, try to find another offset in a where b still occurs
  • If no such offset occurs anymore, you found the longest common character sequence and can begin marking the remaining characters of b in bold

If this is what you would like to achieve, you could try the following improvements on your algorithm:

function compareStrings(a, b) {
  let i = 0;
  let j = 0;
  let search = '';  // current search term (substring of b)

  while (j < b.length) {
    search += b[j];  // add another character of b to search string
    if (a.indexOf(search) > -1) {  // search is found in b, continue
      j++;
    } else {
      return b.substr(j);  // return remaining substring of b which is not part of a
    }
  }
}

console.info(compareStrings('business plan', 'business plafond'));  // fond
console.info(compareStrings('business plan', 'plan and monitoring')); // and monitoring

I've seen that in your original code you also want to skip space characters; however I didn't quite understand whether this behavior would result in erroneous outputs... If you want to ignore whitespace at all, try to use a.replace(/\s/g) (resp. with b).

Upvotes: 2

kshetline
kshetline

Reputation: 13682

Doing text diffs is actually a pretty complicated task, and you might need to fine-tune various parameters of how the diff is performed to get the results you want. I recently tried this:

https://www.npmjs.com/package/diff

And found it to be pretty helpful.

Upvotes: 0

Related Questions