如何处理文本以创建包含一些子字符串的新数组?

时间:2016-06-01 16:32:39

标签: javascript html

我正在编写一个关于html的脚本,我的想法是我要处理一个看起来像这样的文本:

"TW|223SDSDr33|Archive" "Yes"
"TW|ASFFSDFSFASDFS|Name" "LOCALggr"
"TW|AFFSFSFSDFSFASDFS|AFFAckAssocCd" ""
"TW|12AFFFSDFASFSFASDFS|AFFAckCommID" "fsdf"
"TW|FSFASFFSDFSFASDFS|AFFAckLevel" "fsdf Supported"
"TW|AFFSDFAASFSA|AFFAckRqst" "No Requedfst"
"TW|AFFSDFSFASDFS|AFFAckTestInd" "Test"
"TW|sfasfsSFSAFAS|AFFAckVersion" "fsdfs"

我想处理文本以创建一个名为words的数组,该数组包含前一个文本的子字符串,使用管道作为分隔符,如下所示:

words=["TW,223SDSDr33,Archive" "Yes",...,"TW,sfasfsSFSAFAS,AFFAckVersion" "fsdfs"]

为了达到这个目的,我试过了:

var stringArray = document.getElementById("texto").value.split('\n');
document.write(stringArray.toString());
var arrayLength = stringArray.length;
for (var i = 0; i < arrayLength; i++) {
    //Process every line;
}

这保存我的textarea然后处理它,但问题是我不知道如何处理每一行以提取我想要的子字符串,为了更清楚这是完整的代码,我想感谢任何有关实现这一目标的建议,谢谢,无论如何:

<!DOCTYPE html>
<html>

<body>
<p id="demo"></p>

<textarea cols=150 rows=10 id="texto">
"TW|223SDSDr33|Archive" "Yes"
"TW|ASFFSDFSFASDFS|Name" "LOCALggr"
"TW|AFFSFSFSDFSFASDFS|AFFAckAssocCd" ""
"TW|12AFFFSDFASFSFASDFS|AFFAckCommID" "fsdf"
"TW|FSFASFFSDFSFASDFS|AFFAckLevel" "fsdf Supported"
"TW|AFFSDFAASFSA|AFFAckRqst" "No Requedfst"
"TW|AFFSDFSFASDFS|AFFAckTestInd" "Test"
"TW|sfasfsSFSAFAS|AFFAckVersion" "fsdfs"

</textarea>

<script>
var words = [];
var stringArray = document.getElementById("texto").value.split('\n');
document.write(stringArray.toString());
var arrayLength = stringArray.length;
for (var i = 0; i < arrayLength; i++) {
    //Do something;
}




</script>


</body>
</html>

1 个答案:

答案 0 :(得分:1)

我使用了正则表达式和Array.prototype.split。您可以根据要添加到words的内容取消注释。

for (var i = 0; i < arrayLength; i++) {
    var line = stringArray[i];
    var quotes = /"(.*?)" "(.*?)"/.exec(line);
    if (quotes) {
      var first = quotes[1];
      var last = quotes[2];

      var separated = first.split("|");

      // If you want to put the array of words
      words.push(separated);

      // In case you want them joined with a colon
      // words.push(separated.join(","));

      // If you want to add the second word that was in double quotes
      // words.push(last);
    }
}

// Uncomment to see results
// console.log(words);