English | https://blog.stackademic.com/20-useful-javascript-coding-techniques-you-should-know-about-bec185d89f5
Do you know all these skills? Delete cookies, format money, get URL query parameters... These JavaScript skills can greatly improve our work efficiency.
Therefore, in today's article, I have prepared 20 JavaScript tips to share with you.
1. Skills of operating url
01. Obtain the query parameters of the url
I often need to get query parameters of url, for example how to get its value by name?
const url = 'https://medium.com?name=fatfish&age=100'
Do you have any good ideas?
I used to love using regular expressions to solve this problem.
const getQueryByName = (url, name) => {
const queryReg = new RegExp(`${name}=([^?&]*)`, 'i')
const match = url.match(queryReg)
return match ? decodeURIComponent(match[1]) : ''
}
const url = 'https://medium.com?name=fatfish&age=100'
console.log(getQueryByName(url, 'name')) // fatfish
Unfortunately, regular expressions are so complicated that not many people are good at them.
Is there an easier way?
Yes, searchParams is our savior, we need to call its get method to get the answer we want.
That's great!
const getQueryByName2 = (url, name) => {
const searchParams = new URL(url).searchParams
return decodeURIComponent(searchParams.get(name) || '')
}
console.log(getQueryByName2(url, 'name')) // fatfish
02. Get all query parameters of url
My friend, can you tell me how to get all its parameters? We still need to use searchParams.
const getAllQueryParams = (url) => {
const searchParams = new URL(url).searchParams
return Object.fromEntries(searchParams.entries())
}
const url = 'https://medium.com?name=fatfish&age=100'
console.log(getAllQueryParams(url))
/*
{
"name": "fatfish",
"age": "100"
}
*/
03. Add or modify query parameters of url
Friends, you must have encountered the same problem as me.
I need to add some query parameters after url like age=100, height=200.
const url = 'https://medium.com?name=fatfish'
// Please write a function to convert url to url2
const url2 = https://medium.com?name=fatfish&age=100&height=200
I think this is not a very simple matter, we have to consider many situations, such as:
If the name parameter already exists in the url, we should modify it, if not, add it.
const setQueryParams = (url, params) => {
const newUrl = new URL(url)
const searchParams = newUrl.searchParams
Object.entries(params).forEach(([ key, value ]) => {
searchParams.set(key, value)
})
return newUrl.toString()
}
const url = 'https://medium.com?name=fatfish&age=10'
console.log(setQueryParams(url, {
age: 100,
height: 200
}))
// https://medium.com/?name=fatfish&age=100&height=200
I would like to thank searchParams again for making it easier to deal with query parameters for urls.
The setQueryParams function can help us do a lot of things.
Add query parameters
modify query parameters
In the previous example, we changed the age from 10 to 100 and added a height number.
04. Delete the query parameters of the url
Sometimes we need to remove some url's query parameters and generate a new one.
const deleteQueryParams = (url, delParams = []) => {
const newUrl = new URL(url)
const searchParams = newUrl.searchParams
delParams.forEach((key) => searchParams.delete(key))
return newUrl.toString()
}
const url = 'https://medium.com?name=fatfish&age=10&height=200'
const url2 = deleteQueryParams(url, [ 'age', 'height' ])
console.log(url2) // https://medium.com/?name=fatfish
2. Skills for operating cookies
05. Get cookie by name
Browsers don't provide an API for us to get cookies, so we need to write complex logic to solve this problem.
For example:
Assume the following cookie information is stored under www.example.com website.
// BD_UPN=123253; ___rl__test__cookies=1691332234378; OUTFOX_SEARCH_USER_ID_NCOO=279255438.227351
We can get any of these values using the getCookieByName method.
const getCookieByName = (name) => {
const cookies = Object.fromEntries(
document.cookie.split('; ').map(cookie => cookie.split('='))
)
return decodeURIComponent( cookies[ name ] || '' )
}
getCookieByName('OUTFOX_SEARCH_USER_ID_NCOO') // 279255438.227351
getCookieByName('BD_UPN') // 123253
getCookieByName('___rl__test__cookies') // 1691332234378
06. Delete cookies
How can we delete cookies? The answer is to set the expiration time to one second before the current moment.
const deleteCookie = (name) => {
const nowDate = new Date()
nowDate.setTime(nowDate.getTime() - 1000)
document.cookie = `${encodeURIComponent(name)}=;expires=${nowDate.toUTCString()};path=/`
}
deleteCookie('___rl__test__cookies')
getCookieByName('___rl__test__cookies') // ''
07. Set cookies
In addition to getting cookies and deleting cookies, we also need to set cookies
const setCookie = (name, value, millisecondsToExpire, path = '/') => {
const nowDate = new Date()
nowDate.setTime(nowDate.getTime() + millisecondsToExpire)
document.cookie = `${name}=${value}; expires=${nowDate.toUTCString()}; ${path}`
}
setCookie('name', 'fatfish', 3000) // After 3 seconds name will be removed from the cookie
3. About string operations
08. Obtain a random string of specified length
Let me think, when do we need generateRandomString?
Oh, when I need a unique string? Yes, that's why it exists.
const generateRandomString = (len = 10) => {
const chr = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
const chrLen = chr.length
let randomStr = ''
for (let i = 0; i < len; i++) {
const s = Math.floor(Math.random() * chrLen)
randomStr += chr[s]
}
return randomStr
}
09. Remove all spaces in the string
We need to filter the content entered by the user, such as removing all spaces contained in the string.
const removeAllSpaces = (str) => {
return str.replace(/\s/g, "");
}
removeAllSpaces('i am fatfish') // iamfatfish
4. Array operations
10. Shuffle an Array
This might not be a good solution, why?
const shuffleArray = (array) => {
return array.sort(() => Math.random() - 0.5)
}
const arr = [ 'i', 'a', 'f', 'a', 't', 'f', 'i', 's' ]
shuffleArray(arr) // ['i', 'f', 't', 'a', 'f', 's', 'a', 'i']
shuffleArray(arr) // ['i', 'a', 'f', 't', 'i', 'a', 'f', 's']
11. Convert multidimensional array to one-dimensional array
How can I convert this 3D array into a 1D array?
const array = [ 1, [ 2, [ 3 ] ] ] // => [ 1, 2, 3 ]
const flat = (array) => {
return array.reduce((result, it) => {
return result.concat(Array.isArray(it) ? flat(it) : it)
}, [])
}
flat(array) // [1, 2, 3]
Please don't make things so complicated; this function contains recursion and it's giving me a headache.
const array = [ 1, [ 2, [ 3 ] ] ] // => [ 1, 2, 3 ]
// When Infinity is passed in, the array is converted to one-dimensional no matter how many levels it is.
array.flat(Infinity) // [1, 2, 3]
12. Get random value from array
Here's a trick I use a lot, it's simple, but it works for me.
const getRandomValue = (array) => {
return array[ Math.floor(Math.random() * array.length)]
}
const arr = [ 'i', 'a', 'f', 'a', 't', 'f', 'i', 's' ]
getRandomValue(arr) // i
getRandomValue(arr) // a
getRandomValue(arr) // f
5. Digital manipulation
13. Check if it is a number
const isNumber = (s) => {
return /^[-+]?\d+(\.\d+)?$/.test(s)
}
isNumber(10) // true
isNumber('10') // true
isNumber('fatfish') // false
isNumber('10.24') // true
isNumber('+10.24') // true
isNumber('-10.24') // true
isNumber('medium') // false
14. Format currency
Actually, I'm not very good at regular expressions either.
const formatMoney = (num) => {
const numStr = '' + num
return numStr.replace(/\B(?=(\d{3})+(?!\d))/g, ',')
}
formatMoney(123456789) // 123,456,789
formatMoney(123456789.123) // 123,456,789.123
Fortunately, we can easily solve this problem with the help of Intl.NumberFormat.
const formatMoney = (num, code = 'USD') => {
const formatter = new Intl.NumberFormat('en-US', {
style: 'currency',
currency: code,
})
return formatter.format(num)
}
formatMoney(123456789) // $123,456,789
formatMoney(123456789.123) // $123,456,789.12
15. Generate random numbers
How to generate a random number in a specified range?
const getRandomNum = (min, max) => {
return Math.floor(Math.random() * (max - min + 1)) + min
}
getRandomNum(10, 100) // 36
getRandomNum(10, 100) // 80
6. About equipment-related operations
16. isMobile
const isMobile = () => {
const mobileRegex = /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini|Mobile|Tablet/i
return mobileRegex.test(navigator.userAgent)
}
17.isApple
const isApple = () => {
const appleRegex = /iPhone|iPod|iPad/gi;
return appleRegex.test(navigator.userAgent)
}
18.isAndroid
const isAndroid = () => {
const androidRegex = /Android/gi
return androidRegex.test(navigator.userAgent)
}
7. About browser operation
19. Open full screen
const openFullScreen = (element) => {
if (element.requestFullscreen) {
element.requestFullscreen()
} else if (element.mozRequestFullScreen) { // Firefox
element.mozRequestFullScreen()
} else if (element.webkitRequestFullscreen) { // Chrome, Safari, and Opera
element.webkitRequestFullscreen()
} else if (element.msRequestFullscreen) { // IE/Edge
element.msRequestFullscreen()
}
}
20. Exit full screen
const exitFullScreen = () => {
if (document.exitFullscreen) {
document.exitFullscreen();
} else if (document.mozCancelFullScreen) { // Firefox
document.mozCancelFullScreen();
} else if (document.webkitExitFullscreen) { // Chrome, Safari, and Opera
document.webkitExitFullscreen();
} else if (document.msExitFullscreen) { // IE/Edge
document.msExitFullscreen();
}
}
at last
I will share the JavaScript skills here first. If you find it useful, please remember to like me, follow me, and share it with your friends, maybe it can help him.
Thanks for reading, and happy programming!
learn more skills
Please click the public number below