gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 17:57:37 24 4
gpt4 key购买 nike

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

 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com