-1

The input variable contains one or more numeric strings in its character set, not having a fixed size and can have space between letters and numbers. In both cases, I need to identify only the first numerical sequence that appears in the string (it will never be separated by a space). Some examples of the input string:

"a12bcde097fg"  >> return 12
"120abc198672f" >> return 120
"a052bcd123fg"  >> return 052
"a 52 - bcd12"  >> return 52
"A b 123 cd 1"  >> return 123

Is there a way to do this with a single command and be effective in all situations?

Jhw_Trw
  • 152
  • 7
  • 1
    basic reg expression – epascarello May 17 '21 at 18:01
  • 3
    Please [edit] your question to show what research you have done and any attempts you've made to solve the problem yourself. – Heretic Monkey May 17 '21 at 18:02
  • In the meantime, some well-meaning people will post answers because this is a simple task and they can show off their prowess. Their answers do not serve the mission of Stack Overflow, which is to create a knowledge base of high-quality questions and answers. – Heretic Monkey May 17 '21 at 18:05

2 Answers2

3

You could match only digits without global flag.

const 
    getFirstDigits = string => string.match(/\d+/)?.[0] || '',
    array = ["a12bcde097fg", "120abc198672f", "a052bcd123fg", "a 52 - bcd12", "A b 123 cd 1", "a"],
    result = array.map(getFirstDigits);

console.log(result);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
1
const s = "a12bcde097fg";
const r = /(\d+)/.exec(s);
if (r[0]) {
    console.log(r[0]); 
}
jcollum
  • 43,623
  • 55
  • 191
  • 321