javascript - 正则表达式以及将字符串转换为数组以及来回 Javascript

标签 javascript regex arrays string

我正在从文本文件中读取数据,并且我对通过以下内容隔离的特定模式感兴趣:

 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 的模式:所以我只剩下一个自然语言问题或陈述。为了实现这一点,我将数组转换为 string ,然后使用 .split() 创建所需的数组,如下所示:

var nlString = cleanString.toString();
var finalArray = nlString.split(/NL:/gm);

我遇到两个问题。 1. 我最终在结果数组的索引 [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."]

如何消除这些问题?另外,如果有人有一种更优雅的方法来读取由换行符分隔的丑陋的大文本文件并隔离感兴趣的字符串,我会全神贯注。

预先感谢您的任何建议。

最佳答案

您不必将数组转换为字符串,然后删除 NL: 字符串并转换回数组,只需迭代数组并删除每个索引中的该字符串

var arr = arr.map(function(el) {return el.replace('NL:','');});

FIDDLE

如果旧版浏览器有问题,常规的 for 循环也可以工作

关于javascript - 正则表达式以及将字符串转换为数组以及来回 Javascript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20870428/

相关文章:

javascript - jQuery UI 正在禁用 SVG 图像中的链接( xlink :href )

javascript - iCheck 复选框在打印中不可见

javascript - PHP 验证检查记录是否存在

javascript - 是否可以在 javascript 中覆盖 document.location.href?

php - 如何将数组添加到数组中成为二维数组?

c - 如何在 C 中旋转一维数组的一部分?

java - Java中替换字符串的内存高效方法

python - 我如何知道正则表达式 subn 的 repl 函数中的匹配索引

javascript - JS : How to match one capture group multiple times in the same string?

arrays - 不同长度数组之间的平均值