Advertisement
plirof2

Generate #2 hash 0-99 from a string in javascript

Jan 11th, 2024 (edited)
1,349
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. Add hash prefix to href description (innerHtml) that are inside a specific div
  2. =================================================================
  3. // script.js
  4. function addHashLabels() {
  5.   const divprobesrv = document.getElementById('probeserver');  
  6.   //const links = document.getElementsByTagName('a');
  7.   const links = divprobesrv.getElementsByTagName('a');
  8.   const hashRange = 99 - 1 + 1; // 01 to 99
  9.  
  10.   for (let i = 0; i < links.length; i++) {
  11.     const url = links[i].getAttribute('href');
  12.     const hash = getHash(url);
  13.  
  14.     // Generate prefix based on hash number
  15.     const prefixletter=links[i].innerHTML.charAt(0);
  16.     //console.log("InnetHTML="+prefixletter+ " , innerHTML="+links[i].innerHTML)
  17.     const prefix = prefixletter+('0' + (hash % hashRange + 1)).slice(-2);
  18.    
  19.     // Add prefix to link description
  20.     links[i].innerHTML = prefix + ': ' + links[i].innerHTML;
  21.   }
  22. };
  23.  
  24. // Function to generate hash from URL
  25. function getHash(url) {
  26.   let hash = 0;
  27.   for (let i = 0; i < url.length; i++) {
  28.     hash = ((hash << 5) - hash) + url.charCodeAt(i);
  29.     hash = hash & hash; // Convert to 32bit integer
  30.   }
  31.   return Math.abs(hash);
  32. }
  33.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement