首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >从混合字符串的数组中提取数字- Javascript

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

Stack Overflow用户
提问于 2018-09-06 00:18:30
回答 6查看 6K关注 0票数 1

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

代码语言:javascript
复制
const myArr = ['Prihodi 23456 danaci 34 razhodi 23455 I drugi.']

我需要这样做

代码语言:javascript
复制
const filtered = [23456, 34, 23455]

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

EN

回答 6

Stack Overflow用户

回答已采纳

发布于 2018-09-06 00:31:35

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

请参阅MDN了解

map()

替换()

trim()

split()

代码语言:javascript
复制
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);

或者

代码语言:javascript
复制
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);

票数 3
EN

Stack Overflow用户

发布于 2018-09-06 00:28:41

代码语言:javascript
复制
const myArr = ['Prihodi 23456 danaci 34 razhodi 23455 I drugi.'];
var result=[];
myArr.forEach(function(v){
  arr=v.match(/[-+]?[0-9]*\.?[0-9]+/g);
  result=result.concat(arr);
});
const filtered = result.map(function (x) { 
 return parseInt(x, 10); 
   });
console.log(filtered)

票数 2
EN

Stack Overflow用户

发布于 2018-09-06 00:33:53

代码语言:javascript
复制
const myArr = ['Prihodi 23456 danaci 34 razhodi 23455 I drugi.']
const reduced = myArr[0].split(' ').reduce((arr, item) => {
  const parsed = Number.parseInt(item)
  if(!Number.isNaN(parsed)) arr.push(parsed)
  return arr
}, [])
console.log(reduced)

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/52189621

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档