-2

Let say I've String

var str = 'Sumur Bandung'

and

var x = 'Kecamatan Sumur Bandung'

from str and x there are two matching characters Sumur and Bandung. How can I check that str has characters that match with x?

Rimuru Tempest
  • 525
  • 1
  • 4
  • 10

2 Answers2

2

You can use "include", it's the best.

var x = 'Kecamatan Sumur Bandung'
var str = 'Sumur Bandung'
console.log(x.includes(str) || str.includes(x))
djcaesar9114
  • 1,880
  • 1
  • 21
  • 41
  • source is `Sumur Bandung` not `Kecamatan Sumur Bandung` – Rimuru Tempest Jun 09 '20 at 23:28
  • I mean `'Sumur Bandung'.includes('Kecamatan Sumur Bandung')` always return `false`. because in the future I do not know whether the `Kecamatan` is in the first variable or in the second variable – Rimuru Tempest Jun 09 '20 at 23:37
  • @RimuruTempest If the problem is that you don't know which one is the full string then just test both. So using this example that would be `x.includes(str) || str.includes(x)`. – John Montgomery Jun 09 '20 at 23:43
2
let str = "Sumur Bandung";
let x = "Kecamatan Sumur Bandung";

function stringContains(parentString, childString) {
  const parentStringSeparator = parentString.split(" ");
  return childString
  .split(" ")
  .every((word) => parentStringSeparator.includes(word));
}

console.log(stringContains(x, str));

If I understand you correctly, this is what you're asking. Given a parent string separated by spaces, check if every word of a child string is in the parent string.

Edit: This function doesn't take in account word order and splits every string with spaces.

Edit2: If you're trying to ask whether a child string contains at least one word from a parent string, you should use some instead of every:

let str = "Sumur Bandung";
let x = "Kecamatan Sumur Bandung";

function stringContains(parentString, childString) {
  const parentStringSeparator = parentString.split(" ");
  return childString
  .split(" ")
  .some((word) => parentStringSeparator.includes(word));
}

console.log(stringContains(x, str));
Stan Loona
  • 615
  • 9
  • 18