0

This answer helps a lot when we have one word in string and one word in substring. Method includes() do the job. Any idea how to solve this if there is more than one word in string and more then one word in substring? For example:

const string = "hello world";
const substring = "hel wo";

console.log(string.includes(substring)); --> //This is false, but I want to change the code to return true

Should I create some arrays from string and substring using split(" ") and than somehow compare two arrays?

nemostyle
  • 794
  • 4
  • 11
  • 32

2 Answers2

2

You can split the "substring" on whitespace to get an array of all substrings you want to look for and then use Array.prototype.every() to see if all substrings are found:

const string = "hello world";
const substring = "hel wo";

console.log(substring.split(/\s+/).every(substr => string.includes(substr)));
Ivar
  • 6,138
  • 12
  • 49
  • 61
  • 2
    Note that this would also return true for `"wo hel"`. – ray Mar 08 '21 at 15:13
  • 1
    @rayhatfield Good point, though it is not clear from the question that it should not be. – Ivar Mar 08 '21 at 15:25
  • 2
    Right. Just an observation. Wasn't clear whether was desirable or problematic. And the more I think about this the more uncertain I am about what OP is trying to accomplish. Partial words? Starts with? Some of the same characters? – ray Mar 08 '21 at 15:27
  • Now that you mention it, they might also want to match it word for word. (i.e. the first word should contain the first substring etc.) I'll leave my answer up for now. If they clarify I'll update/delete it. (And if they don't clarify, it still might help someone else in the future.) – Ivar Mar 08 '21 at 15:43
  • 1
    @Ivar This is all what I needed, thank you. :) – nemostyle Mar 08 '21 at 16:04
0

you can use regex for this:

var str = "hello world";
var patt = new RegExp(/.{0,}((?:hel)).{0,}((?:wo)).{0,}/ig);
console.log(patt.test(str));
Odinh
  • 183
  • 2
  • 15