stack
stack

Reputation: 10218

How to convert a string to 0 if it isn't containing any digit?

I have this inputs:

var str1 = "21";
var str2 = "1.";
var str3 = "5. test"
var str4 = "- something";

I want this outputs:

// 21
// 1
// 5
// 0


My question seems easy, but that's 30min which I'm thinking about it and still I couldn't solve it.

Upvotes: 0

Views: 72

Answers (4)

krisk
krisk

Reputation: 167

   var patt = /([0-9]+)/,
       match = patt.exec(str);
   if (!match) 
        str = 0;
   else
       str = match[1];

This will match first number from your string.

Upvotes: 1

UserBSS1
UserBSS1

Reputation: 2211

var str4 = "- something"; 
str4 = ( str4.match(/\d+/g)) ? str4 : 0;

Upvotes: 1

Andrew Brooke
Andrew Brooke

Reputation: 12153

isNaN() and parseInt()

var str1 = "21";
var str2 = "1.";
var str3 = "5. test"
var str4 = "- something";

console.log(isNaN(parseInt(str1)) ? 0 : parseInt(str1));
console.log(isNaN(parseInt(str2)) ? 0 : parseInt(str2));
console.log(isNaN(parseInt(str3)) ? 0 : parseInt(str3));
console.log(isNaN(parseInt(str4)) ? 0 : parseInt(str4));

Upvotes: 2

Nicky Mirfallah
Nicky Mirfallah

Reputation: 1054

you can say if the number(yourString) = NaN then print 0

Upvotes: 2

Related Questions