DEV Community

Emmanuel Aiyenigba
Emmanuel Aiyenigba

Posted on

How to get a particular word from a long string in Javascript

slice

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"

Enter fullscreen mode Exit fullscreen mode

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("/");

Enter fullscreen mode Exit fullscreen mode

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);

Enter fullscreen mode Exit fullscreen mode

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)

Collapse
 
emmanuelthecoder profile image
Emmanuel Aiyenigba

Sure, that's another way.

Collapse
 
benjaminreid profile image
Benjamin Reid

Nice one! 👍🏻 You can also use array destructuring for something like this too.

const [, newCity] = city.split("/")
Enter fullscreen mode Exit fullscreen mode
Collapse
 
jonrandy profile image
Jon Randy 🎖️ • Edited

☝ What he said. Although:

const newCity = city.split("/")[1]
Enter fullscreen mode Exit fullscreen mode

is slightly shorter, and arguably more readable.

Collapse
 
emmanuelthecoder profile image
Emmanuel Aiyenigba

I agree. Although my aim here was to try out slice() on strings.