-3

How to find the first number from string in javascript?

var string = "120-250";
var string = "120,250";
var string = "120 | 250";
2
  • regular expression, match start of string and numbers Commented Sep 8, 2022 at 14:07
  • Just use parseInt(string). Commented Sep 8, 2022 at 18:38

2 Answers 2

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
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.