How to Extract the Integer Part of a String in JavaScript?

Estimated read time 1 min read

You can extract the integer part of a string in JavaScript using the parseInt function. The parseInt function takes a string as an argument and returns an integer representation of the string, if possible. By default, parseInt stops parsing the string when it encounters a character that is not a digit, so only the integer part of the string is returned.

Here’s an example:

let str = "123456";
let result = parseInt(str);
console.log(result);
// Output: 123456

In the example, the parseInt function is used to parse the string "123456" and returns the integer 123456.

You can also specify a radix (the base of the number system) as the second argument to the parseInt function. For example:

let str = "11";
let result = parseInt(str, 2);
console.log(result);
// Output: 3

In this example, the parseInt function is used to parse the string "11" as a binary number and returns its decimal equivalent, 3.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply