Q:

Javascript Regex giving NaN from string

I am trying to get only numbers from starting of a string.
i have following code to get numbers and text from a string. 

var unitData = '(135 g)'  // it may be 0.135 or .135
var unitValue = Number(unitData.match(/.?\d+\.?\d*/).toString());
var unitName = unitData.match(/[A-Za-z]+/g) || '';

console.log(unitValue);
console.log(unitName);

its giving NaN for unitValue. It works fine if number are on first position of  a string. 

A:

There is one small mistake that bracket is also picked in your regex.
It was basically returning this:

'(135

I have updated the regex. Please try below :

var unitData = '(135 g)'
var unitValue = Number(unitData.match(/\d*\.?\d+/)[0]);
console.log(unitValue);
unitData = '(.135 g)'
unitValue = Number(unitData.match(/\d*\.?\d+/)[0]);
 console.log(unitValue);
unitData = '(135.42 g)'
unitValue = Number(unitData.match(/\d*\.?\d+/)[0]);
unitName = unitData.match(/[A-Za-z]+/g) || '';

console.log(unitValue);
console.log(unitName);

Hope this helps :)

