javascript 如何在没有正则表达式的情况下从字符串中获取数字

rdrgkggo  于 2023-08-02  发布在  Java
关注(0)|答案(2)|浏览(79)

在不使用regex的情况下,有没有一种方法可以在JavaScript中从字符串中获取number?

例如,如果输入是"id is 12345",那么我希望输出中有12345数字。
我知道很多正则表达式的解决方案,但我正在寻找一个非正则表达式整洁的解决方案。

nhaq1z21

nhaq1z211#

迭代字符并检查它们是否在一组数字中:

const str = 'id is 12345 or 54321';

const set = new Set([...'0123456789']);

const nums = [];
let start = -1;

for (let i = 0; i <= str.length; i++) {
  const c = str[i];
  if (set.has(c)) {
    if(start === -1 ){
      start = i;
    }
  } else {
    start > -1 && nums.push(+str.slice(start, i));
    start = -1;
  }
}

console.log(nums);

字符串
如果你想要最快的解决方案,请使用Unemitted的c >= '0' && c <= '9'String::slice()


的数据

<script benchmark data-count="1">

const str = "abc def 12345 xyz 987".repeat(1000000);

// @benchmark Unmitigated
{
  let res = [], curr = '';
  for (const c of str + ' ') {
    if (c >= '0' && c <= '9') // add || c === '-' (to handle negatives)
      curr += c;
    else if (curr)
      res.push(+curr), curr = '';
      // use BigInt(curr) to handle larger numbers
  }
  res
}

// @benchmark Alexander

{
  const set = new Set([...'0123456789']);

  const nums = [];
  let start = -1;

  for (let i = 0; i <= str.length; i++) {
    const c = str[i];
    if (set.has(c)) {
      if(start === -1 ){
        start = i;
      }
    } else {
      start > -1 && nums.push(+str.slice(start, i));
      start = -1;
    }
  }
  nums
}

// @benchmark Unmitigated + String::slice()
{
  let res = [], start = -1;
  for (let i = 0; i <= str.length; i++) {
    const c = str[i];
    if (c >= '0' && c <= '9') {
      if(start === -1 ){
        start = i;
      }
    } else {
      start > -1 && res.push(+str.slice(start, i));
      start = -1;
    }
  }
  res
}

</script>
<script src="https://cdn.jsdelivr.net/gh/silentmantra/benchmark/loader.js"></script>

olmpazwi

olmpazwi2#

您可以循环遍历所有字符,并从连续的数字中构建数字。
这里有一个解决方案,适用于多个数字(仅使用字符0-9形成)。

const str = "abc def 12345 xyz 987";
let res = [], curr = '';
for (const c of str + ' ') {
  if (c >= '0' && c <= '9') // add || c === '-' (to handle negatives)
    curr += c;
  else if (curr)
    res.push(+curr), curr = '';
    // use BigInt(curr) to handle larger numbers
}
console.log(res);

字符串

相关问题