我正在编写一个脚本来提取我的textarea的单词数组,如下所示:
<textarea cols="150" rows="15" id="texto">
"RBD|X|RBD3|C|92173~GJHGWO.NAYE" "SAMBORNSiPOSSSTHRa1"
"RBD|X|RBD|C|92173~GJHGX4.NAYE" "SAMBORNSiPOSSSTHRa"
"RBD|X3|RBD3|C|92173~GJHGX6.NAYE" "SAMBORNSiPOSSSTHRa1"
"RBD|X|RBD|C|92173~GJHGX8.NAYE" "SAMBORNSiPOSSSTHRa2"
"RBD|X|RBD|C|92173~GJHGXA.NAYE" "SAMBORNSiPOSSSTHRa2"
"RBD|X3|RBD|C|92173~GJHGXC.NAYE" "SAMBORNSiPOSSSTHRa"
</textarea>
我想从这一个获得一个数组,将以下符号视为分隔符:&#34; |&#34;,&#34;〜&#34;和&#34; &#34;因此,我想要的输出将是一个具有以下结构的数组:
["RBD", "X", "RBD3", "C", "92173", "GJHGWO.NAYE", "SAMBORNSiPOSSSTHRa1",...,"SAMBORNSiPOSSSTHRa"]
为了达到这个目的,我试过了:
var text = document.getElementById("texto").value;
console.log(text);
var splitWords = text.split(/[["\|~]/);
console.log(splitWords);
但是因为我得到了失败:
["", "RBD", "X", "RBD3", "C", "92173", "GJHGWO.NAYE", " ", "SAMBORNSiPOSSSTHRa1", "↵", "RBD", "X", "RBD", "C", "92173", "GJHGX4.NAYE", " ", "SAMBORNSiPOSSSTHRa", "↵", "RBD", "X3", "RBD3", "C", "92173", "GJHGX6.NAYE", " ", "SAMBORNSiPOSSSTHRa1", "↵", "RBD", "X", "RBD", "C", "92173", "GJHGX8.NAYE", " ", "SAMBORNSiPOSSSTHRa2", "↵", "RBD", "X", "RBD", "C", "92173", "GJHGXA.NAYE", " ", "SAMBORNSiPOSSSTHRa2", "↵", "RBD", "X3", "RBD", "C", "92173", "GJHGXC.NAYE", " ", "SAMBORNSiPOSSSTHRa", "↵"]
其中包含一些我不想要的符号,例如:&#34;↵&#34;,&#34;&#34;和 &#34; &#34;我想感谢任何修复它的建议。
过去我发布了一个非常相似的问题但当时我想获得一个独特的数组,该结构是:
splitWords = [RBD,X,RBD,C,92173,GJHGWO.NAYE,...,SAMBORNSiPOSSSTHRa]
答案 0 :(得分:1)
您必须删除换行符。
var text = document.getElementById("texto").value;
console.log(text);
// Remove newline chars
text = text.replace(/\n/g, "");
var splitWords = text.split(/[["\|~]/);
console.log(splitWords);
答案 1 :(得分:1)
好的,我们要做的是修剪最后的换行符,执行一系列替换以规范化分隔符,然后在该分隔符处拆分:
var text = document.getElementById("texto").value;
var splitWords = text
.trim('\n')
.replace(/"/g, '')
.replace(/\s|\n|~/g, '|')
.split('|');
console.log(splitWords);
&#13;
<textarea cols="150" rows="15" id="texto">
"RBD|X|RBD3|C|92173~GJHGWO.NAYE" "SAMBORNSiPOSSSTHRa1"
"RBD|X|RBD|C|92173~GJHGX4.NAYE" "SAMBORNSiPOSSSTHRa"
"RBD|X3|RBD3|C|92173~GJHGX6.NAYE" "SAMBORNSiPOSSSTHRa1"
"RBD|X|RBD|C|92173~GJHGX8.NAYE" "SAMBORNSiPOSSSTHRa2"
"RBD|X|RBD|C|92173~GJHGXA.NAYE" "SAMBORNSiPOSSSTHRa2"
"RBD|X3|RBD|C|92173~GJHGXC.NAYE" "SAMBORNSiPOSSSTHRa"
</textarea>
&#13;
答案 2 :(得分:1)
这可能会很好地完成你的工作
var ta = document.getElementById("texto");
arr = texto.value.replace(/"/g,"").replace(/\n$/g,"").replace(/~/g,"|").replace(/\s+/g,"|").split("|");
console.log(arr);
&#13;
<textarea cols="150" rows="15" id="texto">
"RBD|X|RBD3|C|92173~GJHGWO.NAYE" "SAMBORNSiPOSSSTHRa1"
"RBD|X|RBD|C|92173~GJHGX4.NAYE" "SAMBORNSiPOSSSTHRa"
"RBD|X3|RBD3|C|92173~GJHGX6.NAYE" "SAMBORNSiPOSSSTHRa1"
"RBD|X|RBD|C|92173~GJHGX8.NAYE" "SAMBORNSiPOSSSTHRa2"
"RBD|X|RBD|C|92173~GJHGXA.NAYE" "SAMBORNSiPOSSSTHRa2"
"RBD|X3|RBD|C|92173~GJHGXC.NAYE" "SAMBORNSiPOSSSTHRa"
</textarea>
&#13;