IronWaffleMan
IronWaffleMan

Reputation: 2692

Trying to cast string to number returns NaN

I'm confused... I have a number as a string ('3'), and I want it to become a normal Number-type number. If I go into any console and do Number('3'), it'll return 3.

However, in this code it returns NaN:

const attr = "rating='3'";
const [attrName, attrValue] = attr.split('=');
// if the attrValue is a number, cast it as such
if (!Number.isNaN(attrValue)) {
    const numAttr = Number(attrValue);
    console.log('num: ', numAttr, attrValue.length, attrValue.charCodeAt(0));
}

I confirm that the first char code of the number string is 39, which is single apostrophe, and its length is 3, so no sneaky hidden chars.. The numAttr value is NaN though. It also does go into the if statement, which presumably tells me that it can, in fact, become a number?

Upvotes: 1

Views: 850

Answers (1)

Maik Lowrey
Maik Lowrey

Reputation: 17566

You have to replace the single Quotes around the number. You can use the replace() function for this:

const attr = "rating='3'";
let [attrName, attrValue] = attr.split('=');
const para1 = attrName;
const para2 = attrValue.replace(/'/g, '');

console.log(para1, para2);
console.log('isNAN()?',isNaN(para2))

isNaN = is not a Number?

Upvotes: 1

Related Questions