Home > Net >  how to find the first number from string in js(javascript)?
how to find the first number from string in js(javascript)?

Time:09-09

How to find the first number from string in javascript?

var string = "120-250";
var string = "120,250";
var string = "120 | 250";

CodePudding user response:

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

CodePudding user response:

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

  • Related