The easiest way I can see to do this, using a modern browser, is:
$('#search').keyup(function (e) {
// we're splitting on the white-space characters, therefore they don't
// seem a useful character to run this function on:
if (e.which !== 32) {
var searchFieldValue = $('#search').val(),
str = "The sky is awake so I am awake so we have to play",
// splitting the searchFieldValue on white-space (to get
// individual words):
words = searchFieldValue.split(/\W+/),
// using Array.prototype.every() to check that each word entered
// is present in the string; `every()` will return a Boolean,
// true: every element in the array returned true for the condition,
// false: one, or more, element(s) returned false for the condition:
allPresent = words.every(function (a) {
// creating a new Regular Expression for each word
// in order to apply your own approach:
return str.search(new RegExp(a, 'img')) > -1;
});
// just for diagnostic purposes:
console.log(allPresent);
// you could, of course, omit the variable and simply return
// the words.every(function(a){...});
return allPresent;
}
});
JS Fiddle demo.
A slightly cheaper approach (avoiding the creation of mutliple regular expression objects):
$('#search').keyup(function (e) {
if (e.which !== 32) {
var searchFieldValue = $('#search').val(),
str = "The sky is awake so I am awake so we have to play",
words = searchFieldValue.split(/\W+/),
allPresent = words.every(function (a) {
// finding the lowercased word inside of the lowercased string:
return str.toLowerCase().indexOf(a.toLowerCase()) > -1;
});
console.log(allPresent);
return allPresent;
}
});
JS Fiddle demo.
Edited in response to comment from OP:
[Let's] say [that] I have a [string of] 'awakeness'
is there a regex to return false
when the user [enters] 'awake'
only?
Yes, but this does involve using the more expensive multiple-RegExp solution:
$('#search').keyup(function (e) {
if (e.which !== 32) {
var searchFieldValue = $('#search').val(),
str = "awakeness",
words = searchFieldValue.split(/\W+/),
allPresent = words.every(function (a) {
// the change is the following line, which matches word-boundaries:
return str.search(new RegExp("\\b" + a + "\\b", 'img')) > -1;
});
console.log(allPresent);
return allPresent;
}
});
JS Fiddle demo.
References: