清理字符串数组

时间:2015-04-06 16:22:19

标签: javascript string

假设我有一个数组

var documentPredicateValues= [
  "http://schema.org/", 
  "http://schema.org/MusicEvent", 
  "_:2", 
  "_:3", 
  "Shostakovich Leningrad", 
  "2014-05-23T20:00",
  "_:4", "_:6", 
  "http://schema.org/MusicVenue", 
  "Chicago Symphony Center",
  "http://en.wikipedia.org/wiki/Symphony_Center",
  "220 S. Michigan Ave, Chicago, Illinois, USA", 
  "http://schema.org/Offer", 
  "file:///examples/ticket/12341234", 
  "40", 
  "USD", 
  "http://schema.org/InStock", 
  "http://schema.org/CreativeWork", 
  "http://en.wikipedia.org/wiki/Peter_Grimes", 
  "Britten Four Sea Interludes and Passacaglia from Peter Grimes", 
  "http://schema.org/CreativeWork", 
  "http://en.wikipedia.org/wiki/Symphony_No._7_(Shostakovich)", 
  "Shostakovich Symphony No. 7 (Leningrad)", 
  "http://schema.org/MusicGroup", 
  "http://cso.org/", 
  "file:///C:/Users/Ben/Desktop/Visualizaing%20Linked…ptimised(RDFA%20query)/examples/Performer?id=4434", 
  "http://schema.org/Person", 
  "http://www.jaapvanzweden.com/", 
  "file:///examples/jvanzweden_s.jpg", 
  "file:///examples/Performer.aspx?id=11324"
];

我只想“清理”任何以'file'开头的字符串值,直到'/'的最后一个索引我有一段代码(下面),它找到每个以文件开头的字符串然而每当我尝试做一个子字符串并删除不需要的字符,它适用于所有类似的东西:

for(var p =0; p < documentPredicateValues.length; p++)
{       

cleaned.push(documentPredicateValues[p].substring(documentPredicateValues[p].lastIndexOf("/")+1, documentPredicateValues[p].length));  
}

,结果是

[
   "", 
  "MusicEvent", 
  "_:2", 
  "_:3", 
  "Shostakovich Leningrad", 
  "2014-05-23T20:00", 
  "_:4", 
  "_:6", 
  "MusicVenue", 
  "Chicago Symphony Center", 
  "Symphony_Center", 
  "220 S. Michigan Ave, Chicago, Illinois, USA", 
  "Offer", 
  "12341234", 
  "40", 
  "USD", 
  "InStock", 
  "CreativeWork", 
  "Peter_Grimes", 
  "Britten Four Sea Interludes and Passacaglia from Peter Grimes", 
  "CreativeWork", 
  "Symphony_No._7_(Shostakovich)", 
  "Shostakovich Symphony No. 7 (Leningrad)", 
  "MusicGroup", 
  "", 
  "Performer?id=4434", 
  "Person", 
  "", 
  "jvanzweden_s.jpg", 
  "Performer.aspx?id=11324", 
  "12341234", 
  "Performer?id=4434", 
  "jvanzweden_s.jpg", 
  "Performer.aspx?id=11324"
]

这是一个JSfiddle:https://jsfiddle.net/kt9zzx5d/2/

编辑:粘贴错误的功能。 JS小提琴已更新。

1 个答案:

答案 0 :(得分:1)

您使用的过滤器不正确。 Filter将返回与谓词函数匹配的数组元素,而不是用于分配东西。

请改用:

for (var i = 0, l = documentPredicateValues.length; i < l; i++) {
    var e = documentPredicateValues[i];

    documentPredicateValues[i] = e.substring(0,4) == "file" ? e.substring(e.lastIndexOf("/")+1, e.length) : e;
}

或者如果您不想覆盖原始数组:

var cleaned = documentPredicateValues.map(function(e) {
    return e.substring(0,4) == "file" ? e.substring(e.lastIndexOf("/")+1, e.length) : e;
});