Need help understanding regex function

function displayMatches() {
  //get the array of cities matching the keyword
  const matchArray = findMatches(this.value, cities);
  //going through each city
  const html = => {

       const regex = new RegExp(this.value, 'gi');
    //why are we replacing?
    const cityName =, `<span class="hl">${this.value}</span>`);
    const stateName = place.state.replace(regex, `<span class="hl">${this.value}</span>`);
    return `
        <span class="name">${cityName}, ${stateName}</span>
        <span class="population">${numberWithCommas(place.population)}</span>
  suggestions.innerHTML = html;

I am fetching a json file with the names of cities and states. the problem is, the solution of this problem involves regex with replace method and i am unable to understand what is going opn with the code .can someone please help? thanks!

In order to display stuff in HTML, you need to make it a valid HTML element. In this instance, it is a Span.
So you get the city e.g. London, and replace it with <span class=“hl”>London</span> (cityName)
Same goes for state (stateName).

Do you understand basic Regex?
The gi is:
g = go as many times as you find it (not just the first one)
i = ignore uppercase/ lowercase (london, LONDON, London are all found when looking for London)

1 Like

wouldn’t the span only gove this.value not the name of the city?

The $ tells the processor to access a piece of your computer’s memory, referenced (for human benefit) by “this.value”. The computer does not need to know what it is called, only us humans do. So, “this.value” is meaningful to us humans for the purpose of coding.

“this.value” refers to the value (contents of the memory) of “this” element , whatever that is in each case.

Here, the list of cities matching your Search Criteria, is processed, replacing the name of City and State with the Span to display the City and State (as previously explained).
For each element of the array of matching cities, “this” becomes that particular element of the array.

I’ve edited your post for readability. When you enter a code block into a forum post, please precede it with a separate line of three backticks and follow it with a separate line of three backticks to make it easier to read.

You can also use the “preformatted text” tool in the editor (</>) to add backticks around text.

See this post to find the backtick on your keyboard.
Note: Backticks (`) are not single quotes (’).

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.