redditor
redditor

Reputation: 4316

Javascript - JSON string replacement

With some help from fellow stack users I currently have this:

http://jsfiddle.net/XRCvE/

I would like to know what I need to do to edit the code to change the JSON data {location.city} to delete after the first comma so this:

Mansfield, MA, US

becomes

Mansfield

Apologies, I am a beginner, a working jsfiddle would be much appreciated. Thank you.

Upvotes: 0

Views: 121

Answers (3)

Ryan Fiorini
Ryan Fiorini

Reputation: 800

JSFiddle

Just do a split on the , and take the first item:

events[0].location.city = events[0].location.city.split(",")[0];

Upvotes: 3

Brian Hadaway
Brian Hadaway

Reputation: 1893

if(events[0].location.city.indexOf(',') > 0) {
    events[0].location.city = events[0].location.city.split(",")[0];
}

http://jsfiddle.net/XRCvE/4/

Upvotes: 2

Chad Killingsworth
Chad Killingsworth

Reputation: 14411

Here's one way to do it:

if (events[0].location.city.indexOf(',') > 0) {
  events[0].location.city =
      events[0].location.city.substr(0, events[0].location.city.indexOf(','));
}

I've updated the JSFiddle with a working example: http://jsfiddle.net/XRCvE/1/

Upvotes: 2

Related Questions