Ich suche nach einer einfachen Lösung einen String in eine valide Css-id zu wandeln.
Perfekt wäre, wenn die id dann wieder zurück formatiert werden könnte.
Momentan habe ich das hier:
JavaScript
function strToHex(str){ // credits: http://stackoverflow.com/a/21648161
var hex, i;
var result = "";
for (i=0; i<str.length; i++) {
hex = str.charCodeAt(i).toString(16);
result += ("000"+hex).slice(-4);
}
return result
}
function hexToStr(hex){ // credits: http://stackoverflow.com/a/21648161
var j;
var hexes = hex.match(/.{1,4}/g) || [];
var back = "";
for(j = 0; j<hexes.length; j++) {
back += String.fromCharCode(parseInt(hexes[j], 16));
}
return back;
}
var str = "abc-#*´^?",
hex = strToHex(str),
str_back = hexToStr(hex);
console.log(str); // abc-#*´^?
console.log(hex); // 006100620063002d0023002a00b4005e003f
console.log(str_back); // abc-#*´^?
Alles anzeigen
and die id würde ich jetzt noch "p_" vorn anhängen, damit sie nicht mit einer Zahl begint
Wie man aber sieht, ist die id sehr lang.
Jemand ne Idee, wie was ich da noch drüber laufen lassen könnte?