I use the data
attribute to store strings and numbers in DOM nodes and read them with JavaScript. Unfortunately all values in the dataset
are saved as string. So whats is the best way to convert them into numbers but leave the strings.
html:
<input data-minvalue="10" data-startcolor="#00ee00"/>
expected result:
{
minvalue: 10,
startcolor:'#00ee00'
}
Edit:
- it has to work with int and float
- should not convert '12_test'
- should convert '.3'
I use the data
attribute to store strings and numbers in DOM nodes and read them with JavaScript. Unfortunately all values in the dataset
are saved as string. So whats is the best way to convert them into numbers but leave the strings.
html:
<input data-minvalue="10" data-startcolor="#00ee00"/>
expected result:
{
minvalue: 10,
startcolor:'#00ee00'
}
Edit:
- it has to work with int and float
- should not convert '12_test'
- should convert '.3'
5 Answers
Reset to default 5Precede the value by +
, which will convert it to a number natively and preserves stuff like 12_test
, which parseFloat
does not. If the result isNaN
, then safe the string instead.
function kittenBaloon(str) {
var num = +str;
if(isNaN(num)) {
return str;
} else {
return num;
}
}
console.log(kittenBaloon('12_test'));
console.log(kittenBaloon('.3'));
console.log(kittenBaloon('#00ee00'));
Use the Number
function to parse numeric values. If it is not numeric, you get a NaN
.
var dataset = el.dataset;
var data = {};
Object.keys(dataset).forEach(function (key) {
var num = Number(dataset[key]);
data[key] = isNaN(num) ? dataset[key] : num;
})
If parsing the attribute and checking for isFinite
is not enough, you will have to test via regex whether you want to parse it as a number or not:
var obj = {};
for (var i=0; i<node.attributes.length; i++) {
var attr = node.attributes.length;
if (attr.name.substr(0, 5) == "data-")
obj[attr.name.substr(5)] = /^[+-]?(\d*\.)?\d+(e[+-]?\d+)?$/i.test(attr.value)
? parseFloat(attr.value)
: attr.value;
}
}
This regex orientates on the numeric string grammar as found in EcmaScript §9.3.1; yet it for example does not allow whitespaces.
You would use the parseInt() method.
After you pull the attr value for data-minvalue from the html you would pass it to parseInt() and use that as the value in your object.
assuming the use of jquery
var obj = {};
var strNum = $('selector').attr('data-minvalue);
var intNum = parseInt(strNum);
obj.minvalue = intNum;
var string1 = "#456456";
var string2 = "546.789";
var filterString = function (string) {
var temp = string;
regex1 = /\./;
regex2 = /\D/g;
temp = temp.replace(regex1, '');
if (!regex2.test(temp)) {
return parseFloat(string);
}
return string;
}
string1 = filterString(string1);
string2 = filterString(string2);
console.log(typeof string1); //returns string
console.log(typeof string2); //returns number