I'm still learning JavaScript but I just can't seem to find a way to see if a string contains a substring.
Basically I have some Titles of some individuals and I want to see if the Title contains strings like "President" or "Sr" in the title this is what i have so far but does not seem to be working.
var title = "President of Sales";
var arrayOfTitles = ["President","Chief","VP","SVP","Director","Manager","Mrg","Sr","Senior","Executive Assistant","Principle Architect","GM","Technical Advisor"];
var re = new RegExp(arrayOfTitles.join("|"),"i");
for(i = 0; i < arrayOfTitles.length; i++){
if ( re.test(gr.title)){
return;
}
}
However this code will not work with String likes "Jr VP" or "President of Sales". Is there a way to build an array of Regex of these strings?
any help would be great thanks
3 Answers 3
You do not need to run a loop
var title = "President of Sales";
var arrayOfTitles = ["President","Chief","VP","SVP","Director","Manager","Mrg","Sr","Senior","Executive Assistant","Principle Architect","GM","Technical Advisor"];
var regex = new RegExp(arrayOfTitles.join("|"), "i");
//The regex will return true if found in the array
if ( regex.test(title) ){
console.log("has");
}
1 Comment
How about something simple like :
var title = "President of Sales";
var arrayOfTitles = ["President","Chief","VP","SVP","Director","Manager","Mrg","Sr","Senior","Executive Assistant","Principle Architect","GM","Technical Advisor"];
var matches = (function() {
for(var i=0; i < arrayOfTitles.length; i++) {
if(title.indexOf(arrayOfTitles[i]) > -1) { return true; }
}
return false;
}());
Comments
You can also use the includes() function, instead of indexOf().
var title = "President of Sales";
var arrayOfTitles = ["President","Chief","VP","SVP","Director","Manager","Mrg","Sr","Senior","Executive Assistant","Principle Architect","GM","Technical Advisor"];
var matches = (function() {
for(var i=0; i < arrayOfTitles.length; i++) {
if(title.includes(arrayOfTitles[i])) { return true; }
}
return false;
}());
indexOf. If you want a case-insensitive search, apply toLowerCase on string and keywords. And, unless the above is in a function context,returndoesn't make much sense there. Usebreakto leave the loop, and set a flag beforehand if you're interested in the positive or negative outcome of the whole test.arrayOfTitlesshould work, but if you do that you don't need to loop over the same array. Tryre.test(title)without the loop - that worked fine for me.