Anonymous
Anonymous

Reputation: 9

how to get number from string without regex

Without using regex, is there a way to get number from a string in JavaScript?

For example, if input is "id is 12345", then I want 12345 number in output.

I know a lot of regex solutions, but I am looking for a non-regex tidy solution.

Upvotes: -1

Views: 86

Answers (2)

Alexander Nenashev
Alexander Nenashev

Reputation: 23602

Iterate characters and check whether they are in a set of numbers:

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);

If you want the fastest solution use Unmitigated's c >= '0' && c <= '9' and String::slice():

enter image description here

<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>

Upvotes: 2

Unmitigated
Unmitigated

Reputation: 89422

You can loop over all the characters and build up numbers from consecutive digits.

Here is one solution that works for multiple numbers (formed only using the characters 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);

Upvotes: 1

Related Questions