1. Reverse the numbersconst reverseNumber = n => parseFloat(`${n}`.split('').reverse().join('')) * Math.sign(n); reverseNumber(123); // 321 reverseNumber(-200); // -2 reverseNumber(32.4); // 4.23 reverseNumber(-32.4); // -4.23 2. Get the largest n numbers in the arrayconst maxFromArray = (array, number = 1) => [...array] .sort((x, y) => y -x).slice(0, number); maxFromArray([2, 1, 4, 3, 5, 6]); // [6] maxFromArray([2, 1, 4, 3, 6, 6], 2); // [6, 6] 3. Calculate factorialconst factorial = (number) => number < 0 ? (() => { throw new TypeError('Type error'); })() : number <= 1 ? 1 : number * factorial(number - 1); factorial(4); // 24 factorial(10); // 3628800 4. Determine whether the current operating environment is a browserconst isBrowser = () => ![typeof window, typeof document].includes('undefined'); isBrowser(); // false (Node) isBrowser(); // true (browser) 5. Determine whether the current operating environment is Node.jsconst isNode = () => typeof process !== 'undefined' && !!process.versions && !!process.versions.node; isNode(); // true (Node) isNode(); // false (browser) 6. Get the parameters on the urlconst getURLParams = url => (url.match(/([^?=&]+)(=([^&]*))/g) || []).reduce( (a, v) => ( (a[v.slice(0, v.indexOf('='))] = v.slice(v.indexOf('=') + 1)), a ), {} ); getURLParams('qq.com'); // {} getURLParams('https://xx.com?name=tntweb&age=20'); // {name: 'tntweb', age: '20'} 7. Convert rgb(x,x,x) color expression format to object formatconst toRGBObject = rgbStr => { const [red, green, blue] = rgbStr.match(/\d+/g).map(Number); return { red, green, blue }; }; toRGBObject('rgb(100, 150, 200)'); // {red: 100, green: 150, blue: 200} 8. Escape strings for use in HTMLconst escapeHTML = str => str.replace( /[&<>'"]/g, tag => ({ '&': '&', '<': '<', '>': '>', "'": ''', '"': '"' }[tag] || tag) ); escapeHTML('<a href="#" rel="external nofollow" >tntweb</a>'); 9. Unescapes escape HTML charactersconst unescapeHTML = str => str.replace( /&|<|>|'|"/g, tag => ({ '&': '&', '<': '<', '>': '>', ''': "'", '"': '"' }[tag] || tag) ); unescapeHTML('<a href="#">tntweb</a>'); 10. Generate a random integer within a specified rangeconst randomIntegerInRange = (min, max) => Math.floor(Math.random() * (max - min + 1)) + min; randomIntegerInRange(1, 7); // 1 - 7 11. Convert the tilde path to an absolute pathconst reversePath = str => str.replace(/^~($|\/|\\)/, `${require('os').homedir()}$1`); reversePath('~/web'); // '/Users/[userName]/web' 12. Get the current URL without any parameters or fragment identifiersconst getBaseURL = url => url.replace(/[?#].*$/, ''); getBaseURL('https://xx.com/index?name=tntweb&company=tencent'); // https://xx.com/index 13. Return the length of the string in bytesconst byteSize = str => new Blob([str]).size; byteSize('🚗'); // 4 byteSize('Hello World'); // 11 14. Randomly get elements in an arrayconst randomly = arr => arr[Math.floor(Math.random() * arr.length)]; randomly([1, 3, 5, 7, 9, 11]); 15. Check if the string is valid JSONconst isValidJSON = str => { try { JSON.parse(str); return true; } catch (e) { return false; } }; isValidJSON('{"name":"tntweb","age":20}'); // true isValidJSON('{"name":"tntweb",age:"20"}'); // false isValidJSON(null); // true This concludes this article about 15 JavaScript functions worth collecting. For more relevant JavaScript function content, please search 123WORDPRESS.COM’s previous articles or continue to browse the following related articles. I hope everyone will support 123WORDPRESS.COM in the future! You may also be interested in:
|
<<: MySQL database query performance optimization strategy
>>: Implementation of nginx flow control and access control
Table of contents 1. setState() Description 1.1 U...
Why do we need to summarize the browser compatibi...
Prerequisite: Mac, zsh installed, mysql downloade...
1. Abnormal performance of Docker startup: 1. The...
Table of contents 1. Introduction 2. Usage Statel...
MySql Null field judgment and IFNULL failure proc...
Preface Merging or splitting by specified charact...
The company project was developed in Java and the...
1. Install mysql5.6 docker run mysql:5.6 Wait unt...
This article example shares the specific code of ...
Table of contents Preface 1. Create a new Vue pro...
Table of contents Using slots in Vue: slot Scoped...
Awk is an application for processing text files, ...
Document hints using the show-header attribute sh...
Achieve results Implementation Code html <h1 c...