Jevon Cochran
Jevon Cochran

Reputation: 1774

Inserting variables into regular expressions

I'm trying to write code that will allow user to check to see if I have been to a specific country.

I've tried this by getting input from user via prompt. Taking that input, storing it into a variable and then inserting that variable into a regex. From there, I attempted to use the .some method on my array of countries, utilizing the regex and the user input variable to determine whether or not I have been to the country that the user specifies.

var countries = ['US', 'UK', 'Canda', 'Mexico', 'Panama', 'Dominican 
                  Republic', 'Brazil', 'Germany', 'France', 'Portugal',
                  'Spain', 'the Netherlands'];

var userCountry = prompt("Please enter a country", "");

var beenToUserCountry = countries.some(country => 
                        /^userCountry$/i.test(country));

if (beenToUserCountry) {
    document.write(`Yes, I have been to ${userCountry}.`);
  } else {
    document.write(`No, I haven't been to ${userCountry} yet.`);
  }

I expect that the code will print "Yes..." for countries that a part of my countries array and and "No..." for ones that are not. Instead, each country that I insert into the prompt gets me a "No..." Help!

Upvotes: 1

Views: 204

Answers (1)

Titus
Titus

Reputation: 22474

You can use a RegExp object for that, here is an example:

var countries = ['US', 'UK', 'Canda', 'Mexico', 'Panama', 'Dominican Republic', 'Brazil', 'Germany', 'France', 'Portugal',
                  'Spain', 'the Netherlands'];

var userCountry = prompt("Please enter a country", "");

var beenToUserCountry = countries.some(country => 
                        new RegExp(`^${userCountry}$`, "i").test(country));

if (beenToUserCountry) {
    document.write(`Yes, I have been to ${userCountry}.`);
  } else {
    document.write(`No, I haven't been to ${userCountry} yet.`);
  }

As @Bergi has mentioned, you should probably escape userCountry to remove any special characters from it, you can find a good example of how you can do that here

Upvotes: 2

Related Questions