javascript - 从与字符串混合的数组中提取数字 - Javascript
问题描述
我有一个字符串和数字的数组。我需要对数字进行排序或更好地仅提取另一个数组中的数字。这是示例:
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);
推荐阅读
- asp.net - 带有 SQL 事务的 Web Farm(多个前端服务器)中的 ASP.NET
- angular - 初始化 ag-Grid 后如何提供 cellEditorParams?
- sql - 以 hh:min 格式比较 SQLite 中的时间并更改日期名称
- sql - 在 OPENXML sql 的情况下,将数据类型 nvarchar 转换为空 XML 节点的数字时出错
- python - 如何在正面向后看中使用条件括号?
- ios - Swift didSet 调用但不更新 UILabel - iOS 属性观察者
- r - 删除在超过 3 个组中找到的行
- r - Rmarkdown 中的标头未以所需格式显示
- mysql - 如何将变量和数组中的值从控制器发送到模型
- excel - cell.value 上的类型不匹配