Yostky
Yostky

Reputation: 27

How to search for two words in a string?

I am trying to create a function that is able to search for TWO words inside a given string from the user. For example, I would be trying to match "New York" inside of the given string "New York, New York".

I have been playing around with regular expressions for this problem, but I am beginning to think that this isn't the right solution. Any help is greatly appreciated!

//doubleWordedCities is an array of cities that have multiple words making up the name

    const cityCodeGenerator = (doubleWordedCities) => {
            for (let i = 0; i < doubleWordedCities.length; ++i) {
                let currentCity = doubleWordedCities[i].toLowerCase();
                let regex = new RegExp(currentCity);

//string is the input from the user
                let checkString = string.match(regex);
            
                if (checkString) {
                    let city = currentCity;
                    string.replace(currentCity,'');
                    console.log("We've found the city, " + city + '!');
                } 
            }
        }

Upvotes: 0

Views: 200

Answers (1)

Steve Quatrale
Steve Quatrale

Reputation: 360

Quick example here, I'm using .includes() to search each string in the array and return a match.

const cities = [
  'San Francisco, California',
  'Boston, Massachusetts',
  'New York, New York',
  'San Antonio, Texas',
  'Denver, Colorado',
  
];

const result = findCity('New York');

function findCity(city){
  
  $(cities).each((i) => {
    let thisCity = cities[i];
    if (thisCity.includes(city)){
      console.log('Match found! ' + thisCity);
      return thisCity;
    }
  });
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Upvotes: 1

Related Questions