miranda
miranda

Reputation: 69

Removing JSON value that contains certain word in JavaScript

I'm using a large API that contains a JSON file of TV Show information.

The key 'name' contains guest information. Most of them return with the list of guests, however some return as 'Episode [x]'. For example:

for (x in data){
 let title = data[x]._embedded.show.name;
 let guests = data[x].name;
 let airdate = data[x].airdate;

 switch(title){
   // ...
   case 'The Daily Show with Trevor Noah':
      p.innerHTML = airdate + " " + guests;
      noah.appendChild(p);
      console.log(airdate, guests);
      break;
   default:
      break;
 }
}

Guest values return as:

Kevin Young, Antoinette Robertson, Gen. Michael Hayden, David Blaine, Episode 63, Episode 64, Episode 65

I'd like to display just the names, and somehow remove any instance of 'Episode'. I have a few ideas, but I'm new to JavaScript and having some trouble. If more code is necessary to answer this question, I'll update this question. Thanks in advance

Upvotes: 1

Views: 389

Answers (3)

Amr Aly
Amr Aly

Reputation: 3905

You can replace all the instances of Episode [0-9] like so:

var str = "Kevin Young, Antoinette Robertson, Gen. Michael Hayden, David Blaine, Episode 63, Episode 64, Episode 65";

var newStr = str.replace(/,[ ]?Episode[ ]?[0-9]+/g, '');

console.log(newStr);

// Kevin Young, Antoinette Robertson, Gen. Michael Hayden, David Blaine

Upvotes: 0

Briley Hooper
Briley Hooper

Reputation: 1271

If you're looking to only print out items that don't have episode in the title, you could put an if() statement before your switch(), and then use a continue statement if you come across an invalid item to skip it (continue will tell Javascript to basically skip to the next item).

for (x in data){
  let title = data[x]._embedded.show.name;
  let guests = data[x].name;
  let airdate = data[x].airdate;

  if (guests.substr(0, 7) === 'Episode') continue;
  // if the title starts with "Episode", no code after this line will be run for this item

  switch(title){
    // ...
    case 'The Daily Show with Trevor Noah':
      p.innerHTML = airdate + " " + guests;
      noah.appendChild(p);
      console.log(airdate, guests);
    break;
    default:
    break;
  }
}

Upvotes: 1

J S
J S

Reputation: 1188

How about using regex?

var pattern = /(,\s)?Episode\s\d+((,\s)?)/g;
var guests = data[x].name.replace(pattern, "");

Test cases:

var str1 = "Kevin Young, Antoinette Robertson, Gen. Michael Hayden, David Blaine, Episode 63, Episode 64, Episode 65"; 
var str2 = "Episode 63, Episode 64, Episode 65, Kevin Young, Antoinette Robertson, Gen. Michael Hayden, David Blaine"; 
var str3 = "Kevin Young, Antoinette Robertson, Gen. Michael Hayden, David Blaine";
var str4 = "Episode 63, Episode 64, Antoinette Robertson, Episode 65";
var str5 = "Episode 63, Episode 64, Episode 65";
var str6 = "Episode 63";

Upvotes: 1

Related Questions