我正在从一个文本文件中读取数据,我对我用以下内容隔离的特定模式感兴趣:
cleanString = queryString.match(/^NL.*/gm);
这导致数组:
["NL:What are the capitals of the states that border the most populated states?",
"NL:What are the capitals of states bordering New York?",
"NL:Show the state capitals and populations.",
"NL:Show the average of state populations.",
"NL:Show all platforms of Salute generated from NAIs with no go mobility."]
然后我想摆脱所有匹配NL的模式:所以我只剩下一个自然的语言问题或陈述。为此,我将数组转换为字符串,然后使用.split()创建所需的数组,如下所示:
var nlString = cleanString.toString();
var finalArray = nlString.split(/NL:/gm);
我遇到两个问题。 1.我在结果数组中的index [0]处得到一个空字符串的额外值,并且 2.我现在有一个逗号文字附加到数组中的字符串:
["", "What are the capitals of the states that border the most populated states?,",
"What are the capitals of states bordering New York?,",
"Show the state capitals and populations.,",
"Show the average of state populations.,",
"Show all platforms of Salute generated from NAIs with no go mobility."]
如何消除这些问题?此外,如果某人有一个更优雅的方法来阅读由划线和隔离感兴趣的字符串分隔的大丑文本文件,我都是眼睛。
提前感谢任何建议。
答案 0 :(得分:2)
您不必将数组转换为字符串,然后删除NL:
字符串并转换回数组,只需迭代数组并删除每个索引中的字符串
var arr = arr.map(function(el) {return el.replace('NL:','');});
如果旧版浏览器存在问题,那么常规for循环也会起作用
答案 1 :(得分:0)
var finalString = nlString.replace(/NL:/gm, '');
答案 2 :(得分:0)
警告:IE8及以下版本不支持map
。这是另一种选择:
var array = string.split(/\n*NL:/);
array.shift(); // that's it