DEV Community

Brent Vanwildemeersch
Brent Vanwildemeersch

Posted on

[Series] JS Tips & Tricks - Ep. 2

Part 2

In part 2 of this series, we look at creating UUIDs, how to reverse all the characters in a string, and how to capitalize the first letter of a string parameter.

Snippet 4 - Create UUID for the browser

To create a UUID (Universally Unique Identifier) we make use of the built-in Node-module crypto. The function beneath will create a UUID that is compliant with RFC4122.

function createUUIDInBrowser() {
  return ([1e7] + -1e3 + -4e3 + -8e3 + -1e11).replace(/[018]/g, (c) =>
    (c ^ (crypto.getRandomValues(new Uint8Array(1))[0] & (15 >> (c / 4)))).toString(16)
  );
}
Enter fullscreen mode Exit fullscreen mode

Snippet 5 - Reverse the characters in a string

The next snippet is reversing all the characters that are passed in the str parameter. A parameter value of Dev.to will return ot.veD after calling the function.

function reverseString(str) {
  return [...str].reverse().join("");
}
Enter fullscreen mode Exit fullscreen mode

Snippet 6 - Capitalize the first letter of a string

The following Javascript snippet will return the input string with the first character capitalized. You can pass a second variable to the function lowerCaseRestOfString, but this is not required (variable is default false)
The secondary variable will lowercase the rest of the the inputted string

function capitalizeFirstLetterOfString([firstChar, ...restOfChars], lowerCaseRestOfString = false) {
  return first.toUpperCase() + (lowerRest ? rest.join("").toLowerCase() : rest.join(""));
}
Enter fullscreen mode Exit fullscreen mode

Latest comments (0)