JavaScript 30 — Day 6 — Type Ahead

Steven Chen
2 min readDec 2, 2021

--

Auto searching based on user input

This is a great feature for practice and review on a few different concepts.

The Type Ahead exercise revolves around listening for user input and filtering through an array and output any cities or states (and the population) that match the user input.

It’s a gentle refresher for fetch calls if you’re a little rusty but largely I love the use of regex as it is something I haven’t had a lot of practice with. The flags and formatting can be a little tricky but once you have it down it is very useful and a lot more concise in a lot of ways.

To review

If you’re like me and not super well-versed with regex (Regular Expressions) you can take a look at the MDN Docs page for it but admittedly it is a little difficult to parse.

If you’re more of an example based learner like me, you can check out Web Dev Simplified’s take on learning Regular Expressions in 20 minutes.

Something to Note

At the end when Wes is looking to format a number with commas (i.e. 100000 becomes 100,000), he just copies a function from off-screen to handle this.

function numberWithCommas(x) {
return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ‘,’);
}

whereas I’m more a fan of the included JS method toLocaleString. In this case you would need to convert the string to a number and then back to a string so not the most logically elegant but syntactically I like it better:

parseInt(number).toLocaleString(‘en-US’);

You could omit the ‘en-US’ if you do have the U.S. English formatting but I included it as a general solution.

--

--