This article will demonstrate the ways to parse a string in JavaScript.
How to Parse a String in JavaScript?
For parsing a string, use the following methods:
Method 1: Parse an Integer as a String Using “parseInt()” Method
To parse a string into an integer/number type, use the “parseInt()” method. This method is utilized for parsing a string into an integer. It accepts two arguments, the “base” and the “string” to be parsed. The “base” is a number system used in the string and it is an optional parameter. If it is not specified, the method assumes base 10.
Syntax
Following syntax is used for the parseInt() method:
Or:
Example
Create a variable “integerString” and store a string of integer number “13856”:
Call the parseInt() method by passing the string as argument:
Finally, print the result on the console using “console.log()” method:
It can be seen that the string has been successfully parsed as an integer number:
Method 2: Parse a Floating-Point Number as String Using “parseFloat()” Method
For parsing a string into a floating-point number, utilize the “parseFloat()” method. It is utilized for parsing a string into a floating-point/decimal number. It accepts only one argument.
Syntax
Utilize the given syntax for the parseFloat() method:
Example
Create a string of decimal number:
Now, pass the string as an argument in the parseFloat() method, and print result on the console:
console.log(result);
Output
Method 3: Parse a Date as a String Using “Date.parse()” Method
Use the “Date.parse()” method to parse a date string in a Date object. This method parses a date string into a Unix timestamp (time in milliseconds). It also takes one argument, the date string, to be parsed.
Syntax
Follow the below-mentioned syntax for the Date.parse() method:
Example
Create a variable “dateString” that stores a date and time:
Pass the date string in a Date.parse() method for converting it into Unix timestamp:
The output displays time in milliseconds since Jan 1st 1990 to the date:
Method 4: Parse a JSON String Using “JSON.parse()” Method
To parse a JSON string, utilize the “JSON.parse()” method. It is utilized to parse a JSON string into an object. It can accept the JSON string as an argument to be parsed.
Syntax
The given syntax is utilized for the JSON.parse() method:
Example
Create a JSON string:
Invoke the JSON.parse() method and pass a JSON string as argument:
console.log(result);
Output
That’s all about parsing a string in JavaScript.
Conclusion
To parse a string in JavaScript, use “parseInt()”, “parseFloat()” “Date.parse()” or the “JSON.parse()” methods. These methods parse the string into an integer, floating point number, Date object, and Object. This article demonstrated the methods for parsing a string in JavaScript.