-2

I have an array of strings. I'd like to extract a number suffix from a string. Here is an example string array.

let arrayData = [ '99ASD', '01A', '0134-A', '78134:TSX' ]

How can I extract numbers from each string?

Cardoso
  • 962
  • 1
  • 12
  • 30
  • Use the available [`String`](//developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String#instance_methods) and [`RegExp`](//developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/RegExp#instance_methods) methods. See [Reference - What does this regex mean?](/q/22937618/4642212) and the [regex tag wiki](/tags/regex/info) and use regex debuggers like [RegEx101](//regex101.com/). What is the desired result? There are no numbers which are suffixes. Where are your attempts? Stack Overflow isn’t a free code-writing service. – Sebastian Simon Sep 08 '21 at 01:17
  • Thanks for your comment. I am not familiar with RegEx. Would you like to tell me the exact RegEx, plz? – Cardoso Sep 08 '21 at 01:19
  • No need for regex... `arrayData.map(s => parseInt(s, 10))` – Phil Sep 08 '21 at 01:20
  • Try this regex `/^\d+/` if you want to use regex to solve your problem. – Meron Sep 08 '21 at 01:23
  • FYI, if a token comes at the start of something it is a _prefix_. A [_suffix_](https://en.wikipedia.org/wiki/Suffix) comes after – Phil Sep 08 '21 at 01:25

1 Answers1

1

You can try using Array.prototype.map():

The map() method creates a new array populated with the results of calling a provided function on every element in the calling array.

and parseInt():

If parseInt encounters a character that is not a numeral in the specified radix, it ignores it and all succeeding characters and returns the integer value parsed up to that point. parseInt truncates numbers to integer values. Leading and trailing spaces are allowed.

let arrayData = [ '99ASD', '01A', '0134-A', '78134:TSX' ];
let arrayNum = arrayData.map(s => parseInt(s, 10));
console.log(arrayNum);
Mamun
  • 66,969
  • 9
  • 47
  • 59