将特殊字符拆分为数组

时间:2014-07-09 15:38:05

标签: javascript

我的Ajax会返回一大串部门名称,如下所示。

var dept='<list>"32001 Dept of (THE) DOE","32010 Dept of "Health"HHS","32021 Dept of DHS,(12/30/2010)","32024 Dept of H&D","32014 Dept of DOJ","32031 Dept of "DOT", Transport"</list>';

我想用dept编号拆分6个部门并将其放在一个数组中,但描述本身有引号,昏迷和所有特殊字符。 唯一一致的部分是乞讨中的5位数部门 我该如何解决这个问题..

i tried to do..
var start = dept.indexOf("<list>");
var stop = dept.indexOf("</list>");
var deptList = dept.substring(start+7,stop);
var deptlist2 = deptList.split('"');
var deptArr=[];

for(x=0; x<deptlist2.length;x++){
if(deptlist2[x].length>1){
 deptArr.push(deptlist2[x]);
  }
}

期望的输出应该是

32001(THE)DOE的部门 32010“健康”部门HHS
32021国土安全部,(2010年12月30日)
32024 H&amp; D部 32014 DOJ部门 32031“DOT”部门,运输

Thanx为你提供帮助..

2 个答案:

答案 0 :(得分:0)

您可以将字符串拆分为多个字符,即",",然后将它们推送到数组中。

var array = deptList.split('","');

我使用div循环将它们输出到示例中的for

<强> HTML:

<div id="output-panel"></div>

<强> JS:

var dept = '<list>"32001 Dept of (THE) DOE","32010 Dept of "Health"HHS","32021 Dept of DHS,(12/30/2010)","32024 Dept of H&D","32014 Dept of DOJ","32031 Dept of "DOT", Transport"</list>';

var start = dept.indexOf("<list>");
var stop = dept.indexOf("</list>");
var deptList = dept.substring(start + 7, stop);

var array = deptList.split('","');

var newHTML = "";
for (var i = 0; i < array.length; i++) {
    newHTML = newHTML + '<span>' + array[i] + '</span><br/>';
}
$("#output-panel").html(newHTML);

Sample JSFiddle

答案 1 :(得分:0)

假设在部门名称中找不到序列",",您可以这样做:

var dept='<list>"32001 Dept of (THE) DOE","32010 Dept of "Health"HHS","32021 Dept of DHS,(12/30/2010)","32024 Dept of H&D","32014 Dept of DOJ","32031 Dept of "DOT", Transport"</list>';

dept = dept.replace(/<\/?list>/g, '');

result = dept.split('","')

console.log(result);

http://jsbin.com/boqaw/1

然而,这是一个非常糟糕的API,你应该使用JSON或至少XML。