尝试使用拆分提取特定数据

时间:2013-02-09 02:16:44

标签: javascript

我有这个txt文件名contacts.txt,其中包含:

kate|female|kathryn bailey beckinsale|26-jul-1973|#23 underworld drive|(621) 142-7827|kate@lycans.net
jessica|female|jessica claire biel|03-mar-1982|27 texas avenue|(53)2344223|jbiel@yahoo.com
johnny|male|john christopher depp ii|09-jun-1963|711 pirate road|(773) 476-6634|jspaw@piratebay.org

我的脚本是这样的:

function syncText() {
var xhr = new XMLHttpRequest();
xhr.open("get", "data/contacts.txt", false);
xhr.send(null);

  if (xhr.status == 200) {
    var data = xhr.responseText;
    var items = data.split("|");
    items.sort();
    var div = document.getElementById("header2");

  for (var i = 0; i < items.length; i++) {
    var p = document.createElement("p");
    var text = document.createTextNode(items[i]);
    p.appendChild(text);
    div.appendChild(p);
  }
  } else {
    alert("data retrieval failed...");
  }
}

HTML就是这样:

<div id="header2">
  <button onclick="syncText()">Load</button>    
</div>`

我只想追回kat,jessica,johnny ..请帮帮我

1 个答案:

答案 0 :(得分:0)

这应该只能获得名称:

var items = data.split("\n"); // build an array with each lines
// \n or \n\r considering that it is separated with line jumps
// warning: it may also contain an empty value at the end if there's an ending line jump

var names=[];

for (var i=0;i<items.length;i++) {
    names.push( items[i].split("|")[0] ); // read the first value before | and insert it
}

// ...
// whatever is needed to be done with names
// ...