banner
leoking

leoking

前端开发者
tg_channel

Practical JavaScript Code

This article organizes some practical one-liners in JavaScript, very useful~~


Get the value of browser cookies#

Find the cookie value using document.cookie

const cookie = name => `; ${document.cookie}`.split(`; ${name}=`).pop().split(';').shift();

cookie('_ga');
// Result: "GA1.2.1929736587.1601974046"

Convert RGB color to hexadecimal#

const rgbToHex = (r, g, b) => "#" + ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1);

rgbToHex(0, 51, 255);
// Result: #0033ff

Copy to clipboard#

You can easily copy text to the clipboard using navigator.clipboard.writeText

The specification requires using the Permissions API to get "clipboard-write" permission before writing to the clipboard. However, specific requirements vary by browser since this is a new API. For more details, please check the compatibility table and Clipboard availability in Clipboard.

function copyToClipboard(textToCopy) {
            // navigator clipboard requires https or other secure contexts
            if (navigator.clipboard && window.isSecureContext) {
                // navigator clipboard writes text to the clipboard
                return navigator.clipboard.writeText(textToCopy);
            } else {
                // create text area
                let textArea = document.createElement("textarea");
                textArea.value = textToCopy;
                // make text area out of viewport and set it to invisible
                textArea.style.position = "absolute";
                textArea.style.opacity = 0;
                textArea.style.left = "-999999px";
                textArea.style.top = "-999999px";
                document.body.appendChild(textArea);
                textArea.focus();
                textArea.select();
                return new Promise((res, rej) => {
                    // execute copy command and remove the text box
                    document.execCommand('copy') ? res() : rej();
                    textArea.remove();
                });
            }
        }

Check if a date is valid#

Use the following code snippet to check if a given date is valid.

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

isDateValid("December 17, 1995 03:24:00");
// Result: true

Find out which day of the year a date falls on#

const dayOfYear = (date) =>
      Math.floor((date - new Date(date.getFullYear(), 0, 0)) / 1000 / 60 / 60 / 24);

dayOfYear(new Date());
// Result: 272

Capitalize the first letter of an English string#

JavaScript does not have a built-in function to capitalize the first letter, so we can use the following code.

const capitalize = str => str.charAt(0).toUpperCase() + str.slice(1)

capitalize("follow for more")
// Result: Follow for more

Calculate the number of days between two dates#

const dayDif = (date1, date2) => Math.ceil(Math.abs(date1.getTime() - date2.getTime()) / 86400000)

dayDif(new Date("2020-10-21"), new Date("2021-10-22"))
// Result: 366

Clear all cookies#

By accessing cookies using document.cookie and clearing them, you can easily clear all cookies stored on the webpage.

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

Generate a random hexadecimal color#

You can generate a random hexadecimal color using Math.random and padEnd property.

const randomHex = () => `#${Math.floor(Math.random() * 0xffffff).toString(16).padEnd(6, "0")}`;

 console.log(randomHex());
// Result: #92b008

Remove duplicates from an array#

You can easily remove duplicates using Set in JavaScript.

const removeDuplicates = (arr) => [...new Set(arr)];

console.log(removeDuplicates([1, 2, 3, 3, 4, 4, 5, 5, 6]));
// Result: [ 1, 2, 3, 4, 5, 6 ]

Get query parameters from a URL#

You can easily retrieve query parameters from a URL by passing window.location or the raw URL goole.com?search=easy&page=3

const getParameters = (URL) => {
  URL = JSON.parse(
    '{"' +
      decodeURI(URL.split("?")[1])
        .replace(/"/g, '\\"')
        .replace(/&/g, '","')
        .replace(/=/g, '":"') +
    '"}'
  );
  return JSON.stringify(URL);
};

getParameters(window.location);
// Result: { search : "easy", page : 3 }

Or more simply:

Object.fromEntries(new URLSearchParams(window.location.search))
// Result: { search : "easy", page : 3 }

Time handling#

We can log the time from a given date in hour::minutes::seconds format.

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

console.log(timeFromDate(new Date(2021, 0, 10, 17, 30, 0)));
// Result: "17:30:00"

Check if a number is even or odd#

const isEven = num => num % 2 === 0;

console.log(isEven(2));
// Result: True

Calculate the average of numbers#

Use the reduce method to find the average among multiple numbers.

const average = (...args) => args.reduce((a, b) => a + b) / args.length;

average(1, 2, 3, 4);
// Result: 2.5

Scroll to the top#

You can automatically scroll to the top using the window.scrollTo(0, 0) method. Set both x and y to 0.

const goToTop = () => window.scrollTo(0, 0);

goToTop();

Reverse a string#

You can easily reverse a string using split, reverse, and join methods.

const reverse = str => str.split('').reverse().join('');

reverse('hello world');
// Result: 'dlrow olleh'

Check if an array is empty#

One-liner to check if an array is empty, will return true or false

const isNotEmpty = arr => Array.isArray(arr) && arr.length > 0;

isNotEmpty([1, 2, 3]);
// Result: true

Get the user's selected text#

Use the built-in getSelection property to get the user's selected text.

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

getSelectedText();

Shuffle an array#

You can shuffle an array using sort and random methods.

const shuffleArray = (arr) => arr.sort(() => 0.5 - Math.random());

console.log(shuffleArray([1, 2, 3, 4]));
// Result: [ 1, 4, 3, 2 ]

Check if the user's device is in dark mode#

Use the following code to check if the user's device is in dark mode.

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

console.log(isDarkMode)
// Result: True or False

Detailed information about the browser's operating system#

console.log(navigator.platform);

Prevent page refresh using void(0)#

The link below can trigger an alert without reloading the page.

<a href="JavaScript:void(0);" onclick="alert('Well done!')">
  Click Me!
</a>

Validate any email#

function validateEmail(email) {
  var re =
    /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
  return re.test(String(email).toLowerCase());
}

// If you want a simpler version that also accepts Unicode characters. You can use the one below!
function validateEmailUnicode(email) {
  var re =
    /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
  return re.test(String(email).toLowerCase());
}

Get the current URL#

console.log("location.href", window.location.href); // Returns full URL

Detect mobile browsers using regex#

Use regex to return true or false based on whether the user is browsing on a mobile phone.

window.mobilecheck = function () {
  var mobileCheck = false;
  (function (a) {
    if (
      /(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino/i.test(
        a
      ) ||
      /1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test(
        a.substr(0, 4)
      )
    )
      mobileCheck = true;
  })(navigator.userAgent || navigator.vendor || window.opera);
  return mobileCheck;
};

Detect mobile browsers without regex expressions#

Simply run a device list and check if the userAgent matches to detect mobile browsers. This is an alternative solution using regex expressions.

function detectmob() {
  if (
    navigator.userAgent.match(/Android/i) ||
    navigator.userAgent.match(/webOS/i) ||
    navigator.userAgent.match(/iPhone/i) ||
    navigator.userAgent.match(/iPad/i) ||
    navigator.userAgent.match(/iPod/i) ||
    navigator.userAgent.match(/BlackBerry/i) ||
    navigator.userAgent.match(/Windows Phone/i)
  ) {
    return true;
  } else {
    return false;
  }
}

Declare and initialize an array#

// We can initialize an array with a specific size or by specifying values. You might use a single array, but two-dimensional arrays can also be done like this:

const array = Array(5).fill(''); 
// Output
(5) ["", "", "", "", ""]

const matrix = Array(5).fill(0).map(() => Array(5).fill(0))
// Output
(5) [Array(5), Array(5), Array(5), Array(5), Array(5)]
0: (5) [0, 0, 0, 0, 0]
1: (5) [0, 0, 0, 0, 0]
2: (5) [0, 0, 0, 0, 0]
3: (5) [0, 0, 0, 0, 0]
4: (5) [0, 0, 0, 0, 0]
length: 5

Sum, minimum, and maximum values#

// We should utilize the reduce method to quickly find basic mathematical operations.

const array  = [5,4,7,8,9,2];

// Sum
array.reduce((a,b) => a+b);
// Output: 35

// Maximum
array.reduce((a,b) => a>b?a:b);
// Output: 9

// Minimum
array.reduce((a,b) => a<b?a:b);
// Output: 2

Sort arrays of strings, numbers, or objects#

// We have built-in methods sort() and reverse() to sort strings, but what about arrays of numbers or objects?

// Sorting string arrays

const stringArr = ["Joe", "Kapil", "Steve", "Musk"]
stringArr.sort();
// Output
(4) ["Joe", "Kapil", "Musk", "Steve"]

stringArr.reverse();
// Output
(4) ["Steve", "Musk", "Kapil", "Joe"]
// Sorting number arrays

const array  = [40, 100, 1, 5, 25, 10];
array.sort((a,b) => a-b);
// Output
(6) [1, 5, 10, 25, 40, 100]

array.sort((a,b) => b-a);
// Output
(6) [100, 40, 25, 10, 5, 1]
// Sorting object arrays

const objectArr = [ 
    { first_name: 'Lazslo', last_name: 'Jamf'     },
    { first_name: 'Pig',    last_name: 'Bodine'   },
    { first_name: 'Pirate', last_name: 'Prentice' }
];
objectArr.sort((a, b) => a.last_name.localeCompare(b.last_name));
// Output 
(3) [{…}, {…}, {…}]
0: {first_name: "Pig", last_name: "Bodine"}
1: {first_name: "Lazslo", last_name: "Jamf"}
2: {first_name: "Pirate", last_name: "Prentice"}
// length: 3

Filter out falsy values from an array#

// Falsy values like 0, undefined, null, false, "", '' can be easily filtered out using the following trick.

const array = [3, 0, 6, 7, '', false];
array.filter(Boolean);

// Output
// (3) [3, 6, 7]

Use logical operators to handle conditional situations#

function doSomething(arg1){ 
    arg1 = arg1 || 10; 
// If arg1 has no value, take the default value 10
}

let foo = 10;  
foo === 10 && doSomething(); 
// If foo equals 10, just execute doSomething();
// Output: 10

foo === 5 || doSomething();
// is the same thing as if (foo != 5) then doSomething();
// Output: 10

Remove duplicate values#

const array  = [5,4,7,8,9,2,7,5];
array.filter((item,idx,arr) => arr.indexOf(item) === idx);
// or
const nonUnique = [...new Set(array)];
// Output: [5, 4, 7, 8, 9, 2]

Create a counter object or Map#

// In most cases, you can count the frequency of certain special words by creating an object or Map.

let string = 'kapilalipak';

const table={}; 
for(let char of string) {
  table[char]=table[char]+1 || 1;
}
// Output
// {k: 2, a: 3, p: 2, i: 2, l: 2}
// or

const countMap = new Map();
  for (let i = 0; i < string.length; i++) {
    if (countMap.has(string[i])) {
      countMap.set(string[i], countMap.get(string[i]) + 1);
    } else {
      countMap.set(string[i], 1);
    }
  }
// Output
// Map(5) {"k" => 2, "a" => 3, "p" => 2, "i" => 2, "l" => 2}

Ternary operators are cool#

function Fever(temp) {
    return temp > 97 ? 'Visit Doctor!'
      : temp < 97 ? 'Go Out and Play!!'
      : temp === 97 ? 'Take Some Rest!': 'Go Out and Play!';
}

// Output
// Fever(97): "Take Some Rest!" 
// Fever(100): "Visit Doctor!"

Comparison of loop methods#

for and for..in default get the index, but you can use arr[index].
for..in also accepts non-numbers, so avoid using it.
forEach, for...of directly get the elements.
forEach can also get the index, but for...of cannot.

Merge two objects#

const user = { 
 name: 'Kapil Raghuwanshi', 
 gender: 'Male' 
 };
const college = { 
 primary: 'Mani Primary School', 
 secondary: 'Lass Secondary School' 
 };
const skills = { 
 programming: 'Extreme', 
 swimming: 'Average', 
 sleeping: 'Pro' 
 };

const summary = {...user, ...college, ...skills};

// Merged multiple objects
gender: "Male"
name: "Kapil Raghuwanshi"
primary: "Mani Primary School"
programming: "Extreme"
secondary: "Lass Secondary School"
sleeping: "Pro"
swimming: "Average"

Arrow functions#

Arrow function expressions are an alternative to traditional function expressions, but they have limitations and cannot be used in all situations. They have lexical scoping (parent scope) and do not have their own this and arguments, so they reference the environment that defines them.

const person = {
name: 'Kapil',
sayName() {
    return this.name;
    }
}
person.sayName();
// Output
"Kapil"

// But like this:

const person = {
name: 'Kapil',
sayName : () => {
    return this.name;
    }
}
person.sayName();
// Output
"

Optional chaining#

const user = {
  employee: {
    name: "Kapil"
  }
};
user.employee?.name;
// Output: "Kapil"
user.employ?.name;
// Output: undefined
user.employ.name
// Output: VM21616:1 Uncaught TypeError: Cannot read property 'name' of undefined

Nullish coalescing operator#

const foo = null ?? 'my school';
// Output: "my school"

const baz = 0 ?? 42;
// Output: 0

Rest and spread syntax#

function myFun(a,  b, ...manyMoreArgs) {
   return arguments.length;
}
myFun("one", "two", "three", "four", "five", "six");

// Output: 6
// And

const parts = ['shoulders', 'knees']; 
const lyrics = ['head', ...parts, 'and', 'toes']; 

lyrics;
// Output: 
(5) ["head", "shoulders", "knees", "and", "toes"]

Shuffle an array#

Utilize the built-in Math.random() method.

const list = [1, 2, 3, 4, 5, 6, 7, 8, 9];
list.sort(() => {
    return Math.random() - 0.5;
});
// Output
(9) [2, 5, 1, 6, 9, 8, 4, 3, 7]
// Output
(9) [4, 1, 7, 5, 3, 8, 2, 9, 6]

Default parameters#

const search = (arr, low=0, high=arr.length-1) => {
    return high;
}
console.log(search([1,2,3,4,5]))
// Output: 4

Convert decimal to binary or hexadecimal#

const num = 10;

num.toString(2);
// Output: "1010"
num.toString(16);
// Output: "a"
num.toString(8);
// Output: "12"

Use destructuring to swap two numbers#

let a = 5;
let b = 8;
[a,b] = [b,a]

[a,b]
// Output
(2) [8, 5]

One-liner palindrome check#

function checkPalindrome(str) {
  return str == str.split('').reverse().join('');
}
checkPalindrome('naman');
// Output: true

Convert Object properties to an array of properties#

const obj = { a: 1, b: 2, c: 3 };

Object.entries(obj);
console.log(Object.entries(obj))
// Output
(3) [Array(2), Array(2), Array(2)]
0: (2) ["a", 1]
1: (2) ["b", 2]
2: (2) ["c", 3]
length: 3

Object.keys(obj);
(3) ["a", "b", "c"]

Object.values(obj);
(3) [1, 2, 3]

When JavaScript is disabled, the code block inside <noscript> will be executed, usually used to display alternative content when the page is generated using JavaScript.#

<script type="javascript">
    // JS related code goes here
</script>
<noscript>
    <a href="next_page.html?noJS=true">JavaScript is disabled on the page. Enable it asap!</a>
</noscript>

Set the cursor to wait#

function myFunction() {
  window.document.body.style.cursor = "wait";
}

Add CSS to console messages#

console.log(
  "%c The text has a purple color, with large font and white background",
  "color: purple; font-size: x-large; background: white"
);

Disable right-click on the webpage#

<body oncontextmenu="return false;"></body>

Capture the browser's back button#

You can do this using the beforeunload event, which is triggered when the window, document, and its resources are about to be unloaded. This event helps warn users that they will lose current data and detect back button events.

 window.addEventListener('beforeunload', () => {
   console.log('Clicked browser back button');
 });
Loading...
Ownership of this post data is guaranteed by blockchain and smart contracts to the creator alone.