This article 整理了一些实用的 JavaScript single-line codes, very useful~~
Get Browser Cookie Value#
Find cookie
value using document.cookie
const cookie = name => `; ${document.cookie}`.split(`; ${name}=`).pop().split(';').shift();
cookie('_ga');
// Result: "GA1.2.1929736587.1601974046"
Convert Color RGB 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#
With navigator.clipboard.writeText
, you can easily copy text to the clipboard.
The specification requires using the Permissions API to get "clipboard-write" permission before writing to the clipboard. However, specific requirements vary by browser, as 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 and 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 be 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 text box
document.execCommand('copy') ? res() : rej();
textArea.remove();
});
}
}
Check if 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 the Day of the Year for a Date#
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 a 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 using document.cookie
to access cookies and clear them, you can easily clear all cookies stored in the webpage.
const clearCookies = document.cookie.split(';').forEach(cookie => document.cookie = cookie.replace(/^ +/, '').replace(/=.*/, `=;expires=${new Date(0).toUTCString()};path=/`));
Generate 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 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 URL#
You can easily retrieve query parameters from the 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 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 Top#
You can use the window.scrollTo(0, 0)
method to automatically scroll to the top. 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 line of code checks if an array is empty, returning true
or false
.
const isNotEmpty = arr => Array.isArray(arr) && arr.length > 0;
isNotEmpty([1, 2, 3]);
// Result: true
Get User Selected Text#
Use the built-in getSelection
property to get the text selected by the user.
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 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 Browser Operating System#
console.log(navigator.platform);
Prevent Page Refresh with 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 Current URL#
console.log("location.href", window.location.href); // Returns full URL
Detect Mobile Browser 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 Browser Without regex Expression#
Simply run a device list and check if the userAgent
matches to detect mobile browsers. This is another 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 Arrays#
// We can initialize an array with a specific size or initialize the array content by specifying values. You might use a set of arrays, and actually, 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 leverage 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 trick below.
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 Operator is 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 Looping Methods#
for and for..in default get index, but you can use arr[index].
for..in also accepts non-numbers, so avoid using it.
forEach, for...of directly get elements.
forEach can also get 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. Because they have lexical scope (parent scope), and do not have their own this and arguments, 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]
Single-line Palindrome Check#
function checkPalindrome(str) {
return str == str.split('').reverse().join('');
}
checkPalindrome('naman');
// Output: true
Convert Object Properties to Property Array#
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, Typically Used to Display Alternative Content When JavaScript is Used to Generate the Page#
<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 Cursor to Wait#
function myFunction() {
window.document.body.style.cursor = "wait";
}
Add CSS to Console Information#
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 Webpage#
<body oncontextmenu="return false;"></body>
Capture Browser Back Button#
You can use the beforeunload
event to do this, 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');
});