I was working with this API recently that returns Africa/Lagos as the timezone data. I needed just the city after the "/". Keep in mind that in this case that city is "Lagos" but it could be any city at all. The API could return Casablanca, New York or just any city depending on the IP address (I was working with IP address).
I needed just the city (not the continent) for me to pass to the map parameter in order to display a location on the map.
How did I do this
I needed to write just a few lines of code to get this done. Yeah, just a few lines.
Let me work you through it.
Let's kind of declare the data in a binding in this example (since we are not using an API here)
const city = "Africa/Lagos"
Now let's extract the city after the "/". Remember it could be any city at all.
To get this city, we first have to find the position of "/" in the string.
const city = "Africa/Lagos"
const cityIndex = city.indexOf("/");
If you log cityIndex
to the console, it returns 6 which is the position of "/". This is dynamic, it will always get the correct position of "/" regardless of how long or short the string could be (from the API response).
So, how do we extract the city after "/" now that we have gotten the index.
const city = "Africa/Lagos"
const cityIndex = city.indexOf("/");
const newCity = city.slice(cityIndex + 1);
If you log newCity
to the console, you will get Lagos as the value.
slice()
was employed here to help us get the word whose first letter starts from position 7.
You can read more on slice().
Top comments (4)
Sure, that's another way.
Nice one! ππ» You can also use array destructuring for something like this too.
β What he said. Although:
is slightly shorter, and arguably more readable.
I agree. Although my aim here was to try out slice() on strings.