0

I would like to detect strings that have prefixes from another. In my case these are separate it by dots. For more understanding I give some examples.

I took a look over thesse posts but in my case does not work 100%.

Determine if one string is a prefix of another

How to check if a string "StartsWith" another string?

I have implemented the following code but the problem is that the example number 5 is false

if(child.substr(0, parent.length) != parent){
  //different prefixes
}

I expect following outputs:

false:

1. parent="abc.xyz"
child="abc.xyz.pol"

2. parent="abc.xyz"
child="abc.xyz.pol.del"

3. parent="abc.xyz.pol"
child="abc.xyz.pol.del"

true:

4. parent="abc.xyz.pol"
child="abc.xyz.del"

5. parent="abc.xyz"
child="abc.xyzDel"

6. parent="abc.xyz"
child="abc.xyzDel.pol"

karlihnos
  • 415
  • 1
  • 7
  • 22

1 Answers1

0

It took me a while to figure out the pattern. Apparently you want to look at each sub-component individually and only return true if the sub-component is not matching. It appears that if there are more sub-components, that it is not being checked/scanned towards the parent string.

Eventually I got this function

function test(p, c) {
  const pSplit = p.split('.');
  const cSplit = c.split('.');
  const maxLen = pSplit.length; // I guess parent has always min # of parts
  for(let i = 0; i < maxLen; ++i) {
    if (pSplit[i] !== cSplit[i]) return true;
  }
  return false;
}

Interactive example:

function test(p, c) {
  const pSplit = p.split('.');
  const cSplit = c.split('.');
  const maxLen = pSplit.length; // I guess parent has always min # of parts
  for(let i = 0; i < maxLen; ++i) {
    if (pSplit[i] !== cSplit[i]) return true;
  }
  return false;
}


console.log('expected to be false');
console.log(test("abc.xyz","abc.xyz.pol"));
console.log(test("abc.xyz","abc.xyz.pol.del"));
console.log(test("abc.xyz.pol","abc.xyz.pol.del"));

console.log('expected to be true');
console.log(test("abc.xyz.pol","abc.xyz.del"));
console.log(test("abc.xyz","abc.xyzDel"));
console.log(test("abc.xyz","abc.xyzDel.pol"));
KarelG
  • 5,176
  • 4
  • 33
  • 49