Killer JavaScript One Liners

shshank

Shshank

Posted on July 22, 2022

Killer JavaScript One Liners

Some useful JavaScript One-Liners

After a good response from the community, I decided to post some few more JavaScript one liners, that might help you a lot. I have posted a link to my previous article of Some useful JavaScript One Liners

Clear All Cookies

const clearCookies = document.cookie.split(';').forEach((cookie) => (document.cookie = cookie.replace(/^ +/, '').replace(/=.*/, `=;expires=${new Date(0).toUTCString()};path=/`)));
Enter fullscreen mode Exit fullscreen mode

Reverse a String

You can reverse a string in one line using split, join and reverse methods.

const strReverse = str => str.split('').reverse().join('');
strReverse('Shshank');
// knahshS
Enter fullscreen mode Exit fullscreen mode

Generate a Random Hex

This method generates a random hex code using Math.random() and padEnd().

const hexClr = () => '#' + Math.floor(Math.random() * 0xffffff).toString(16).padEnd(6, '0');
console.log(hexClr());
Enter fullscreen mode Exit fullscreen mode

Capitalise a String

Javascript doesn't have an inbuilt capitalise function, so we can use the following code of the purpose.

let str = 'follow Shshank for amazing posts';
let capStr = str.replace(/\w\S*/g, (w) => (w.replace(/^\w/, (c) => c.toUpperCase())));
console.log(capStr);
Enter fullscreen mode Exit fullscreen mode

Copy to Clipboard

Easily copy any text to clipboard using navigator.clipboard.writeText.

const copy = (text) => navigator.clipboard.writeText(text);
copy('Shshank');
Enter fullscreen mode Exit fullscreen mode

Hope you like this post. If you find this post useful, please like and share with fellow developers. Follow me for more such posts.

Thank you.

💖 💪 🙅 🚩
shshank
Shshank

Posted on July 22, 2022

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

🤖CMD+C🤖CMD+V? 🛑 Never More!
javascript 🤖CMD+C🤖CMD+V? 🛑 Never More!

June 9, 2023

Y U NO USE the JS native APIs?
javascript Y U NO USE the JS native APIs?

January 14, 2023

Killer JavaScript One Liners
javascript Killer JavaScript One Liners

July 22, 2022