How to extract a JSON object depending on symbol?

Viewed 42

I have this JSON.stringify object (not an array),

  "city": "Tokyo,Japan,Asia",

which can be like this too :

"city": "London"

I want to extract only the first item if there is a coma, and everything if there isn't a coma.

1 Answers

You can use the split property to achieve this

const city1 = "Tokyo,Japan,Asia"

const city2 = "London"

city1.split(',')[0]
city2.split(',')[0]
Related