Answer the question
In order to leave comments, you need to log in
Why doesn't Array.forEach see the first argument?
regExSearch : function(searchString, name) {
var separatedItem = name.toLowerCase().split(' ');
var result;
separatedItem.forEach(function(item) {
var re = new RegExp("^" + searchString);
result = re.test(item);
if (result) return;
});
return result;
},
Answer the question
In order to leave comments, you need to log in
No errors, the given code works fine:
The logic suffers though - the line is if (result) return;
meaningless - the function will be interrupted anyway. And result
, most likely, should not be overwritten when the string does not match the regular expression (as a result, the function returns true for the strings ' Yaroslav ' and ' Ivan Yaroslavovich ', and false for ' Yaroslav Ivanovich ' ).
In general, the whole code can be reduced to this:
function regExSearch(searchString, name) {
var re = new RegExp("^" + searchString);
var words = name.toLowerCase().split(' ');
return !!words.find((item) => re.test(item));
}
function regExSearch(searchString, name) {
var words = name.toLowerCase().split(' ');
return !!words.find((item) => item.startsWith(searchString));
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question