generate random string for div id

后端 未结 12 725
旧时难觅i
旧时难觅i 2020-12-04 17:03

I want to display YouTube videos on my website, but I need to be able to add a unique id for each video that\'s going to be shared by users. So I put this toget

12条回答
  •  一整个雨季
    2020-12-04 17:42

    Based on HTML 4, the id should start from letter:

    ID and NAME tokens must begin with a letter ([A-Za-z]) and may be followed by any number of letters, digits ([0-9]), hyphens ("-"), underscores ("_"), colons (":"), and periods (".").

    So, one of the solutions could be (alphanumeric):

      var length = 9;
      var prefix = 'my-awesome-prefix-'; // To be 100% sure id starts with letter
    
      // Convert it to base 36 (numbers + letters), and grab the first 9 characters
      // after the decimal.
      var id = prefix + Math.random().toString(36).substr(2, length);
    

    Another solution - generate string with letters only:

      var length = 9;
      var id = Math.random().toString(36).replace(/[^a-z]+/g, '').substr(0, length);
    

提交回复
热议问题