删除包含JavaScript中某些单词的JSON值

时间:2018-05-01 00:28:16

标签: javascript html json regex parsing

我正在使用包含电视节目信息的JSON文件的large API

密钥'name'包含访客信息。他们中的大多数都带着客人名单返回,但有些人回复为“剧集[x]”。例如:

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

访客值返回为:

Kevin Young,Antoinette Robertson,将军Michael Hayden,David Blaine,第63集,第64集,第65集

我想只显示名称,并以某种方式删除“Episode”的任何实例。我有一些想法,但我是JavaScript新手并遇到麻烦。如果需要更多代码来回答这个问题,我会更新这个问题。提前致谢

3 个答案:

答案 0 :(得分:1)

如果您打算只打印标题中没有episode的项目,可以在if()之前添加switch()语句,然后使用{ {3}}语句如果您遇到无效项目以跳过它(continue将告诉Javascript基本上跳到下一个项目。)

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

答案 1 :(得分:1)

如何使用正则表达式?

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

测试用例:

    public static boolean isDivisible(int number) {
        for (int i = 2; i <= 9; i++) {
            if (num % i != 0) {
                return false;
            }
        }
        return true;
    }

答案 2 :(得分:0)

您可以像这样替换Episode [0-9]的所有实例:

&#13;
&#13;
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
&#13;
&#13;
&#13;