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?

2 Answers 2

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)));

Sign up to request clarification or add additional context in comments.

5 Comments

Note that this would also return true for "wo hel".
@rayhatfield Good point, though it is not clear from the question that it should not be.
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?
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 This is all what I needed, thank you. :)
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));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.