gpt4 book ai didi

javascript - Javascript 中的方括号正则表达式

转载 作者:行者123 更新时间:2023-11-28 02:32:51 24 4
gpt4 key购买 nike

我有一个这种类型的 JSON 数组:

[ 
{ text: '[Chapter1](chapter1.html)'},
{ text: '[Chapter2](chapter2.html)'},
{ text: '[Chapter3](chapter3.html)'},
{ text: '[Chapter4](chapter4.html)'}
]

尝试循环数组并获取括号中的文本(第 1 章、第 2 章等)I found a RegExp here at StackOverflow .

var aResponse = JSON.parse(body).desc; // the array described above
var result = [];
var sectionRegex = /\[(.*?)\]/;
for(var x in aResponse) {
result.push(sectionRegex.exec(aResponse[x].text));
//console.log(aResponse[x].text) correctly returns the text value
}
console.log(result);

应该打印:

["Chapter1","Chapter2","Chapter3","Chapter4"]

但是我在多个数组中得到奇怪的长结果:

[ '[Chapter1]',
'Chapter1',
index: 0,
input: '[Chapter1](chapter1.html)' ]
[ '[Chapter2]',
'Chapter2',
index: 0,
input: '[Chapter2](chapter2.html)' ]
[ '[Chapter3]',
'Chapter3',
index: 0,
input: '[Chapter3](chapter3.html)' ]
[ '[Chapter4]',
'Chapter4',
index: 0,
input: '[Chapter4](chapter4.html)' ]

我错过了什么?我对正则表达式很烂。

最佳答案

The exec method of regular expressions不仅返回匹配的文本,还返回许多其他信息,包括输入、匹配索引、匹配文本和所有捕获组的文本。您可能想要匹配组 1:

result.push(sectionRegex.exec(aResponse[x].text)[1]);

除此之外,您不应该使用 for(...in...) 循环来循环数组,因为如果将任何方法添加到 Array 中,这将会中断> 的原型(prototype)。 (例如,forEach 垫片)

关于javascript - Javascript 中的方括号正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13872666/

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