DEV Community

Cover image for 19 Practical ES6 Snippets to Solve Common JS Problems 🚀💯
Madza
Madza Subscriber

Posted on • Originally published at madza.hashnode.dev

19 Practical ES6 Snippets to Solve Common JS Problems 🚀💯

In our developer workflow, we often encounter challenging problems that might require just a few lines of code to be solved. In this article, I attempted to compile useful snippets that may assist you when working with URLs, DOM, events, dates, user preferences, and so on.

All of the snippets were handpicked from 30 seconds of code. It's an awesome resource, I would highly recommend going to check it out for more stuff.

The main criterion for curating these was practical usability. Hopefully, you will find something valuable, that you can apply in your future codebases.


1. How to get the base URL?

const getBaseURL = url => url.replace(/[?#].*$/, '');

getBaseURL('http://url.com/page?name=Adam&surname=Smith');
// 'http://url.com/page'
Enter fullscreen mode Exit fullscreen mode

2. How to check if the URL is absolute?

const isAbsoluteURL = str => /^[a-z][a-z0-9+.-]*:/.test(str);

isAbsoluteURL('https://google.com'); // true
isAbsoluteURL('ftp://www.myserver.net'); // true
isAbsoluteURL('/foo/bar'); // false
Enter fullscreen mode Exit fullscreen mode

3. How to get URL parameters as object?

const getURLParameters = url =>
  (url.match(/([^?=&]+)(=([^&]*))/g) || []).reduce(
    (a, v) => (
      (a[v.slice(0, v.indexOf('='))] = v.slice(v.indexOf('=') + 1)), a
    ),
    {}
  );

getURLParameters('google.com'); // {}
getURLParameters('http://url.com/page?name=Adam&surname=Smith');
// {name: 'Adam', surname: 'Smith'}
Enter fullscreen mode Exit fullscreen mode

4. How to check if the element contains another element?

const elementContains = (parent, child) =>
  parent !== child && parent.contains(child);

elementContains(
  document.querySelector('head'),
  document.querySelector('title')
);
// true
elementContains(document.querySelector('body'), document.querySelector('body'));
// false
Enter fullscreen mode Exit fullscreen mode

5. How to get all the ancestors of the element?

const getAncestors = el => {
  let ancestors = [];
  while (el) {
    ancestors.unshift(el);
    el = el.parentNode;
  }
  return ancestors;
};

getAncestors(document.querySelector('nav'));
// [document, html, body, header, nav]
Enter fullscreen mode Exit fullscreen mode

6. How to smooth-scroll element into view?

const smoothScroll = element =>
  document.querySelector(element).scrollIntoView({
    behavior: 'smooth'
  });

smoothScroll('#fooBar'); // scrolls smoothly to the element with the id fooBar
smoothScroll('.fooBar');
// scrolls smoothly to the first element with a class of fooBar
Enter fullscreen mode Exit fullscreen mode

7. How to handle click outside the element?

const onClickOutside = (element, callback) => {
  document.addEventListener('click', e => {
    if (!element.contains(e.target)) callback();
  });
};

onClickOutside('#my-element', () => console.log('Hello'));
// Will log 'Hello' whenever the user clicks outside of #my-element
Enter fullscreen mode Exit fullscreen mode

8. How to generate UUID?

const UUIDGeneratorBrowser = () =>
  ([1e7] + -1e3 + -4e3 + -8e3 + -1e11).replace(/[018]/g, c =>
    (
      c ^
      (crypto.getRandomValues(new Uint8Array(1))[0] & (15 >> (c / 4)))
    ).toString(16)
  );

UUIDGeneratorBrowser(); // '7982fcfe-5721-4632-bede-6000885be57d'
Enter fullscreen mode Exit fullscreen mode

9. How to get the selected text?

const getSelectedText = () => window.getSelection().toString();

getSelectedText(); // 'Lorem ipsum'
Enter fullscreen mode Exit fullscreen mode

10. How to copy text to the clipboard?

const copyToClipboard = str => {
  if (navigator && navigator.clipboard && navigator.clipboard.writeText)
    return navigator.clipboard.writeText(str);
  return Promise.reject('The Clipboard API is not available.');
};
Enter fullscreen mode Exit fullscreen mode

11. How to add styles to HTML element?

const addStyles = (el, styles) => Object.assign(el.style, styles);

addStyles(document.getElementById('my-element'), {
  background: 'red',
  color: '#ffff00',
  fontSize: '3rem'
});
Enter fullscreen mode Exit fullscreen mode

12. How to toggle full-screen mode?

const fullscreen = (mode = true, el = 'body') =>
  mode
    ? document.querySelector(el).requestFullscreen()
    : document.exitFullscreen();

fullscreen(); // Opens `body` in fullscreen mode
fullscreen(false); // Exits fullscreen mode
Enter fullscreen mode Exit fullscreen mode

13. How to detect if Caps lock is on?

<form>
  <label for="username">Username:</label>
  <input id="username" name="username">

  <label for="password">Password:</label>
  <input id="password" name="password" type="password">
  <span id="password-message" style="display: none">Caps Lock is on</span>
</form>
Enter fullscreen mode Exit fullscreen mode
const el = document.getElementById('password');
const msg = document.getElementById('password-message');

el.addEventListener('keyup', e => {
  msg.style = e.getModifierState('CapsLock')
    ? 'display: block'
    : 'display: none';
});
Enter fullscreen mode Exit fullscreen mode

14. How to check if the Date is valid?

const isDateValid = (...val) => !Number.isNaN(new Date(...val).valueOf());

isDateValid('December 17, 1995 03:24:00'); // true
isDateValid('1995-12-17T03:24:00'); // true
isDateValid('1995-12-17 T03:24:00'); // false
isDateValid('Duck'); // false
isDateValid(1995, 11, 17); // true
isDateValid(1995, 11, 17, 'Duck'); // false
isDateValid({}); // false
Enter fullscreen mode Exit fullscreen mode

15. How to get colon time from Date?

const getColonTimeFromDate = date => date.toTimeString().slice(0, 8);

getColonTimeFromDate(new Date()); // '08:38:00'
Enter fullscreen mode Exit fullscreen mode

16. How to generate UNIX timestamp from Date?

const getTimestamp = (date = new Date()) => Math.floor(date.getTime() / 1000);

getTimestamp(); // 1602162242
Enter fullscreen mode Exit fullscreen mode

17. How to check the preferred language of the current user?

const detectLanguage = (defaultLang = 'en-US') =>
  navigator.language ||
  (Array.isArray(navigator.languages) && navigator.languages[0]) ||
  defaultLang;

detectLanguage(); // 'nl-NL'
Enter fullscreen mode Exit fullscreen mode

18. How to check the preferred color scheme of the user?

const prefersDarkColorScheme = () =>
  window &&
  window.matchMedia &&
  window.matchMedia('(prefers-color-scheme: dark)').matches;

prefersDarkColorScheme(); // true
Enter fullscreen mode Exit fullscreen mode

19. How to check if the device supports touch events?

const supportsTouchEvents = () =>
  window && 'ontouchstart' in window;

supportsTouchEvents(); // true
Enter fullscreen mode Exit fullscreen mode

Writing has always been my passion and it gives me pleasure to help and inspire people. If you have any questions, feel free to reach out!

Connect me on Twitter, LinkedIn and GitHub!

Visit my Blog for more articles like this.

Top comments (23)

Collapse
 
mikcat profile image
mikcat

I find easy to use the URL object to manage urls.

const url = new URL("https://example.com/login?user=someguy&page=news");

url.origin
// "https://example.com"
url.host
// "example.com"
url.protocol
// "https:"
url.pathname
// "/login"
url.searchParams.get('user')
// "someguy"
Enter fullscreen mode Exit fullscreen mode

You can get useful localization info from the Intl package. For example:

const {locale, timeZone} = Intl.DateTimeFormat().resolvedOptions();
Enter fullscreen mode Exit fullscreen mode
Collapse
 
madza profile image
Madza

Thanks for the input 👍✨💯

Collapse
 
urstrulyvishwak profile image
Kurapati Mahesh

Great Article @madza

I want to provide few other ways for each of the above:

1

1.
url.indexOf('?');
41
url.slice(0,41);
> 'http://url.com/page'

2.
url.href.split('?')[0];
> 'http://url.com/page'

// If it is the same page url then we can get using location.
location.origin + location.pathname;
'http://url.com/page'
Enter fullscreen mode Exit fullscreen mode

2.

const isAbsolute = (url) => {
  const link = document.createElement('a');
  link.href = url;
  return link.origin + link.pathname + link.search + link.hash === url;
};
Enter fullscreen mode Exit fullscreen mode

3.

const sampleObj = {};
'http://url.com/page?name=Adam&surname=Smith'.split('?')[1].split('&').forEach(item => {
    const temp = item.split('=');
    sampleObj[temp[0]] = temp[1];
});
Enter fullscreen mode Exit fullscreen mode

8.

crypto.randomUUID();
> '41c43cfa-e5d9-4053-bb10-123357d580d4'
Enter fullscreen mode Exit fullscreen mode
Collapse
 
birowo profile image
birowo

3.

Object.fromEntries('http://url.com/page?name=Adam&surname=Smith'.split('?')[1].split('&').map(x=>x.split('=')))
Enter fullscreen mode Exit fullscreen mode
Collapse
 
madza profile image
Madza

Super neat one liner, thanks 👍💯

Collapse
 
madza profile image
Madza

Valuable input, thanks a lot 💖👍💯

Collapse
 
martygo profile image
Martins Gouveia

Currently, we don't need more JS to add smooth-scroll, only CSS is sufficient.

html {
scroll-behavior: smooth;
}

Article very useful. Thanks for sharing with us.

Collapse
 
tleperou profile image
Thomas Lepérou

Since Safari 15.4, we can finally use CSS -- and its JS API, 🙌

Collapse
 
madza profile image
Madza

Useful input, thanks for addition 💯👍

Collapse
 
addin profile image
Akhul Syaifudin

Hello @madza,

I ask permission to rewrite it in my country's language.
Thank you.

Collapse
 
madza profile image
Madza • Edited

Sure, just put reference to this article, include my socials and mention 30 seconds of code in the intro 👍💯✨

Collapse
 
sarma_akondi_746f338b83b7 profile image
Sarma Akondi

Awesome sharing as always 😀

Collapse
 
madza profile image
Madza

Thanks a lot 👍💯✨

Collapse
 
annie profile image
Annie

Hello, I love your article. Can I reprint and translate your article? I will include a link to the article.

Collapse
 
madza profile image
Madza

Sure, just put reference to this article, include my socials and mention 30 seconds of code in the intro 👍💯✨

Collapse
 
annie profile image
Annie

okay, I will.

Thread Thread
 
madza profile image
Madza

Awesome 👍💯💖

Collapse
 
walebee01 profile image
Osho Wale

Great Content

Collapse
 
madza profile image
Madza

Thanks a lot 👍💯✨

Collapse
 
andrewbaisden profile image
Andrew Baisden

Great list of snippets.

Collapse
 
madza profile image
Madza

Thanks a lot, Andrew 👍💯✨

Collapse
 
bobbyiliev profile image
Bobby Iliev

Great content as always!

Collapse
 
madza profile image
Madza

Thank you so much, Bobby! 👍✨💯