Categories
JavaScript Answers

How to parse string to an int in JavaScript?

Spread the love

Sometimes, we want to parse string to an int in JavaScript.

In this article, we’ll look at how to parse string to an int in JavaScript.

How to parse string to an int in JavaScript?

To parse string to an int in JavaScript, we can use a regex to extract the digits from the string.

Then we can use parseInt to convert the string to a number.

For instance, we write:

const s = 'abc123';
const str = s.match(/\d+$/);
const number = parseInt(str, 10);
console.log(number)

to call s.match with a regex to return the digits part of s.

Then we call parseInt with str and 10 to return a number converted from str.

We pass in 10 to return a decimal number.

Therefore, number is 123.

Conclusion

To parse string to an int in JavaScript, we can use a regex to extract the digits from the string.

Then we can use parseInt to convert the string to a number.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *