Reputation: 10218
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
Number();
..replace(/(\d)/g, "$1");
.0
if it isn't containing number.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
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
Reputation: 2211
var str4 = "- something";
str4 = ( str4.match(/\d+/g)) ? str4 : 0;
Upvotes: 1
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