Skip to content

Instantly share code, notes, and snippets.

@netsi1964
Created July 24, 2016 20:19
Show Gist options
  • Save netsi1964/4e1b081d35a8d74701b486125696f7fa to your computer and use it in GitHub Desktop.
Save netsi1964/4e1b081d35a8d74701b486125696f7fa to your computer and use it in GitHub Desktop.
String method to convert to and from a data attribute
String.prototype.toDataProp = function() {
var min = "A".charCodeAt(0),
max = "Z".charCodeAt(0),
res = "data-";
this.split("").forEach(function(char, i) {
var cc = char.charCodeAt(0);
if (cc >= min && cc <= max) {
res += ((i > 0) ? "-" : "") + String.fromCharCode(cc + 32);
} else {
res += char;
}
});
return res;
}
String.prototype.fromDataProp = function() {
var min = "A".charCodeAt(0),
max = "Z".charCodeAt(0),
res = "",
temp = this.split('data-')[1];
temp.split("-").forEach(function(word, i) {
if (i > 0) {
res += String.fromCharCode(word.charCodeAt(0) - 32) + word.substr(1, word.length - 1);
} else {
res += word;
}
});
return res;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment