-3

How to find the first number from string in javascript?

var string = "120-250";
var string = "120,250";
var string = "120 | 250";
epascarello
  • 204,599
  • 20
  • 195
  • 236

2 Answers2

1

Here is an example that may help you understand.

Use the search() method to get the index of the first number in the string.

The search method takes a regular expression and returns the index of the first match in the string.

const str = 'one 2 three 4'

const index = str.search(/[0-9]/);
console.log(index); // 4

const firstNum = Number(str[index]);
console.log(firstNum); // 2
Roy
  • 398
  • 2
  • 12
0

Basic regular expression start of string followed by numbers /^\d+/

const getStart = str => str.match(/^\d+/)?.[0];

console.log(getStart("123,456"));
console.log(getStart("123-456"));
console.log(getStart("123|456"));
console.log(getStart("xxx,xxx"));

Or parseInt can be used, but it will drop leading zeros.

const getStart = str => parseInt(str, 10);

console.log(getStart("123,456"));
console.log(getStart("123-456"));
console.log(getStart("123|456"));
console.log(getStart("xxx,xxx"));
epascarello
  • 204,599
  • 20
  • 195
  • 236