简体   繁体   English

摆脱字符串Javascript中的多余字符

[英]Getting Rid of Extraneous Characters in a String-Javascript

I am loading data about NBA games from an API using Javascript, and I want to manipulate it but am having trouble. 我正在使用Javascript从API加载有关NBA游戏的数据,我想对其进行操作,但遇到了麻烦。 Each game is its own separate object, and is the data is returned like this: 每个游戏都是其自己的单独对象,并且数据是这样返回的:

Date: "Nov 7, 2014"
Opponent: "@ Charlotte"
Result: "L"
Score: "122-119"
Spread: "+1.5"

Depending on whether the team is home or away, there is either a "@" or a "vs" in front of the name of the opponent for that particular game. 根据球队是家乡还是客场,在该场比赛的对手名字前面有一个“ @”或“ vs”。 I want to get rid of this, so that the "Opponent" key only has "Charlotte" as its value in the above example. 我想摆脱这种情况,因此在上面的示例中,“ Opponent”键只有“ Charlotte”作为其值。

I've tried using 我试过使用
gameLog[i].Opponent = (gameLog[i].Opponent.split(" ").pop

to get rid of any characters before the space, but this ruins the data when there is a team name with a space in it like "New York" or "Los Angeles" 删除空格之前的所有字符,但是当其中有一个带有“ New York”或“ Los Angeles”之类的空格的团队名称时,这会破坏数据

This takes the string, and creates a new substring starting at the index of the first white space. 这将获取字符串,并从第一个空格的索引开始创建一个新的子字符串。 eg: 例如:

@ New York = a new string starting after the @. @ New York = @之后的新字符串。 -> New York ->纽约

gameLog[i].Opponent = gameLog[i].Opponent.substr(gameLog[i].Opponent.indexOf(' ')+1);

I guess, something along these lines might help. 我想,遵循这些思路可能会有所帮助。

var home = "@ Charlotte";
var opponent = "vs New York";

function parse(team){

    // Case when it is a home team
    if ( team.indexOf("@") === 0 ){

    return team.replace("@","").trim();

  // Away team
  } else {

    return team.replace("vs","").trim();

  }

}

console.log( parse(home) );
console.log( parse(opponent) );
gameLog[i].Opponent = (gameLog[i].Opponent.split(" ").slice(1).join(" "));
  1. Split based off space character 基于空格字符拆分
  2. Slice off the first item in the array 分割数组中的第一项
  3. Join the contents of the array back together with space. 将数组的内容与空间重新连接在一起。

You need the substr() method: 您需要substr()方法:

var str = "@ Charlotte";
var res = str.substr(2);

Result: Charlotte 结果: Charlotte

Unless there is also a space after "vs", which is not clear. 除非“ vs”后还有空格,否则不清楚。

Then you could use: 然后,您可以使用:

var str = "@ Charlotte";
var res = str.substr(str.indexOf(' ')+1);

You can use regular expressions to replace unwanted characters while looping over an array of objects. 在循环对象数组时,可以使用正则表达式替换不需要的字符。

for (var i = 0; i < arr.length; i++) {
      arr[i].Opponent = arr[i].Opponent.replace(/@\s|vs\s/g, '');
}

Here's a jsbin 这是一个jsbin

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM