最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

How can I convert all numbers in a dataset of a DOM node into JavaScript numbers - Stack Overflow

programmeradmin2浏览0评论

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'
Share Improve this question edited Oct 25, 2012 at 12:45 Andreas Köberle asked Oct 25, 2012 at 12:29 Andreas KöberleAndreas Köberle 111k58 gold badges280 silver badges307 bronze badges
Add a ment  | 

5 Answers 5

Reset to default 5

Precede 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
发布评论

评论列表(0)

  1. 暂无评论