Search code examples
javascriptjavascript-objects

How to convert a random string to a unique and ID friendly string in javascript


Given many random strings in javasript, for example:

str1 = "1%&2xy 232=2"
str2 = "2$$2xy 232=2"
str3 = "ls dlsdl fs§$02"

So the string may contain spaces, numbers, $, %, &, all kinds of chars.

Now let's say I want to generate html elements, one element for each string:

<div id="???">str1</div>
<div id="???">str2</div>
<div id="???">str3</div>

How can I add ids to each element that is created by each string itself? Removing unwanted chars won't work because different strings can result in the same ID. I also want to avoid $('div:contains(str)') as I'm looking for a way to generate unique and reproducible IDs.

I thought about converting each string to hexadecimal and prepend "a" as IDs can not start with a number.

But does anyone knows a better way to do that?


Solution

  • If you are restricted to using ids, convert to base64 using btoa:

    // Prefix with a letter since it is possible for a base64 string to start with a number.
    element.id = "i" + btoa(str1); // "1%&2xy 232=2" -> "MSUmMnh5IDIzMj0y"
    

    If this is not a requirement, use a data attribute instead:

    <div data-str="1%&2xy 232=2">str1</div>
    <div data-str="2$$2xy 232=2">str2</div>