Home > Software design >  Check if the end of one string matches the begining of another string
Check if the end of one string matches the begining of another string

Time:09-16

I have two strings:

let string1 = "Some text here";
let string2 = "text here as well";

I would like to check if the end part of string1 matche the start of string2.

I'm outputting string1 string2. In my case I don't want to print the same words twice. For example, I don't want to print "Some text heretext here as well".

How to I check for this? I have tried startsWith/endsWith and a loop by spiting the string from space. But i don't think my approach is correct as the matching part of strings can vary in length.

Strings can also contain dashes. For example it can be like:

let string1 = "Some-text here";
let string2 = "text here as well";

In the above example the ideal output will be "Some-text here as well".

CodePudding user response:

You can use String.substring to get substrings of both input values, from the end of string1 and the start of string2. If these are the same, we've found our overlap.

let string1 = "Some-text here";
let string2 = "text here as well";

let overlap = null;
for(let i = 1; i <= string1.length; i  ) {
     if (string1.substring(string1.length - i) === string2.substring(0, i)) {
         overlap = string2.substring(0, i);
         break;
     }
}

console.log('Overlap:', overlap);

let concatenated = string1.replace(overlap, '')   string2;

console.log('string1   string2:',concatenated);

CodePudding user response:

Here is a possible brute-force solution:

let resultIdx = 0;
for (let idx = 0; idx < Math.min(string1.length, string2.length); idx  ) {
    if (string2.substring(0, idx) === string1.substring(string1.length - idx)) {  
      resultIdx = idx
    }
 }
let result = string1   string2.substring(resultIdx)

We loop over the strings and check if any substrings match. If so, we save the last index and use it to build the solution (saved in variable result). Is this what you want to find?

CodePudding user response:

let string1 = "Some-text here";
let string2 = "text here as well";
let splitString1 = string1.split(" ");
let splitString2 = string2.split(" ");
let stringSet1 = new Set(splitString1);
let stringSet2 = new Set(splitString2);

console.log(stringSet1);
console.log(stringSet2);

function wordDiff(strSet1, strSet2) {
  let _wordDiff = new Set(stringSet1);
  
  for (let elem of stringSet2) {
    if (_wordDiff.has(elem)) {} else {
      _wordDiff.add(elem);
    }
  }
  
  return _wordDiff;
}

let result = wordDiff(stringSet1, stringSet2);

console.log(result);

  • Related