Created
July 24, 2016 20:19
-
-
Save netsi1964/4e1b081d35a8d74701b486125696f7fa to your computer and use it in GitHub Desktop.
String method to convert to and from a data attribute
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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