gpt4 book ai didi

javascript - 从与字符串混合的数组中提取数字 - Javascript

转载 作者:行者123 更新时间:2023-11-30 09:20:23 25 4
gpt4 key购买 nike

我有一个由字符串和数字组成的数组。我需要对数字进行排序或更好地只提取另一个数组中的数字。这是示例:

 const myArr = ['Prihodi 23456 danaci 34 razhodi 23455 I drugi.']

我需要做成这样

 const filtered = [23456, 34, 23455]

我使用 split(' ') 方法用逗号分隔它们,但不知道如何为 JS 过滤它们,它们都是字符串。

最佳答案

这可能是一个可能的解决方案,

请参阅 MDN 了解 map()replace()trim()split()

const myArr = ['Prihodi 23456 danaci 34 razhodi 23455 I drugi.'];
filtered = myArr[0].replace(/\D+/g, ' ').trim().split(' ').map(e => parseInt(e));
console.log(filtered);

const regex = /\d+/gm;
const str = `Prihodi 23456 danaci 34 razhodi 23455 I drugi`;
let m;
const filter = [];
while ((m = regex.exec(str)) !== null) {
// This is necessary to avoid infinite loops with zero-width matches
if (m.index === regex.lastIndex) {
regex.lastIndex++;
}

// The result can be accessed through the `m`-variable.
m.forEach((match, groupIndex) => {
filter.push(parseInt(match))
});
}

console.log(filter);

关于javascript - 从与字符串混合的数组中提取数字 - Javascript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52189621/

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