gpt4 book ai didi

javascript - 在 javascript 中,如何在数组中搜索子字符串匹配项

转载 作者:IT王子 更新时间:2023-10-29 03:03:26 25 4
gpt4 key购买 nike

我需要在 javascript 中搜索一个数组。搜索将仅针对要匹配的字符串的一部分,因为字符串会分配有附加编号。然后我需要返回成功匹配的数组元素和完整的字符串。

var windowArray = new Array ("item","thing","id-3-text","class");

我需要搜索其中包含 "id-" 的数组元素,我还需要提取元素中的其余文本(即 "id-3 -text").

谢谢

最佳答案

如果您能够使用 Underscore.js在您的项目中, _.filter() 数组函数使这变得轻而易举:

// find all strings in array containing 'thi'
var matches = _.filter(
[ 'item 1', 'thing', 'id-3-text', 'class' ],
function( s ) { return s.indexOf( 'thi' ) !== -1; }
);

迭代器函数可以做任何你想做的事,只要它为匹配返回 true 即可。效果很好。

2017-12-03 更新:
现在这是一个非常过时的答案。也许不是大批量中性能最高的选项,但它可以更简洁地编写 很多 并使用原生 ES6 数组/字符串方法,如 .filter().includes() 现在:

// find all strings in array containing 'thi'
const items = ['item 1', 'thing', 'id-3-text', 'class'];
const matches = items.filter(s => s.includes('thi'));

注意 <= IE11 不支持 String.prototype.includes()(请注意,Edge 可以工作),但是您可以使用 polyfill,或者只是退回到 indexOf()

关于javascript - 在 javascript 中,如何在数组中搜索子字符串匹配项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4556099/

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