agarc
agarc

Reputation: 65

how to check if a string contains a substring from an array of strings in JavaScript

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

Upvotes: 0

Views: 139

Answers (3)

Ben Schmeltzer
Ben Schmeltzer

Reputation: 191

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

Upvotes: 0

Meligy
Meligy

Reputation: 36594

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

Upvotes: 1

alessandrio
alessandrio

Reputation: 4370

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

Upvotes: 1

Related Questions