JavaScript functions

Adding some of the JavaScript functions which could use in your projects. Most of them are from my React projects using as functional components in Helper.js file.

Unique id function

This can be used when needs to generate unique ids for the item. I have created this for generating unique ids for new space and section in DocuSpace.

function getUniqueId(){
  return (
    Math.random()
      .toString(36)
      .substring(2, 15) +
    Math.random()
      .toString(36)
      .substring(2, 15)
  );
};

Using unique id function in React JS

If you want to use it in React project as functional components you can add export this function as shown below

export const getUniqueId = () => {
  return (
    Math.random()
      .toString(36)
      .substring(2, 15) +
    Math.random()
      .toString(36)
      .substring(2, 15)
  );
};

URI Generation / Slugify

If you want to generate URIs based on given string you can use the following function. This will convert spaces as hyphen and remove special characters from the given string. So the final value will be a search engine friendly URI for given text.


function slugify(str, delimeter){
  if (delimeter == null) {
    delimeter = "-";
  }

  str = replaceAccents(str);
  str = str.replace(/[^0-9a-zA-Z\xC0-\xFF \-]/g, "");
  str = str.trim().replace(/ +/g, delimeter).toLowerCase(); 
  return str;
};

Nish

Full stack developer, and Pega Certified Lead System architect since 2013 and with nearly 16 years experience in Pega. Connect with me in Linked in at https://www.linkedin.com/in/msnish/

Leave a Reply

Your email address will not be published. Required fields are marked *