Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node.js Parsing A Number Inside a String

Given a string like:

Recipient: [email protected]
Action: failed
Status: 5.0.0 (permanent failure)
Diagnostic: No

How do I get the "5.0.0" and "permanent failure" only if it's always after Status: ? ?

Thanks

like image 227
donald Avatar asked Apr 23 '11 14:04

donald


People also ask

How can I extract a number from a string in JavaScript?

The number from a string in javascript can be extracted into an array of numbers by using the match method. This function takes a regular expression as an argument and extracts the number from the string. Regular expression for extracting a number is (/(\d+)/).

How do I cast a number in node JS?

You can convert a string to a number in Node. js using any of these three methods: Number() , parseInt() , or parseFloat() .

What does number parseInt () do?

The Number. parseInt() method parses a string argument and returns an integer of the specified radix or base.


1 Answers

var regex = /Status: ([0-9\.]+) \(([a-zA-Z ]+)\)/
var result = string.match(regex);
var statusNumber = result[1];
var statusString = result[2];

You should extend these: [0-9\.], [a-zA-Z ] selectors if you expect other characters in these values. For now the first one expects numbers and dots, the second characters and spaces

like image 87
Máthé Endre-Botond Avatar answered Sep 23 '22 11:09

Máthé Endre-Botond