42 Tips and Tricks to Write Faster, Better-Optimized JavaScript Code
Tags: Front End Development, Web Development, Typescript, Programming, JavaScript

42 Tips and Tricks to Write Faster, Better-Optimized JavaScript Code

Optimize your JavaScript code using modern techniques, tips, and tricks

I always used to prefer something like a newspaper which give enough information in a shorter span of time. Here, I create tips for day to day Frontend development.

You might be doing angular development for a long time but sometimes you might be not updated with the newest features which can solve your issues without doing or writing some extra codes. This can cover some frequently asked Angular topics in interviews 2021. This can cover some frequently asked TypeScript interview topics in 2021. Moreover, these topics can help you to prepare yourself for JavaScript interviews in 2021.

Here I am coming with a new series to cover some tips which helped me in my day-to-day coding.

1. Sort an array of objects by string property value

It can be done in different ways.

1. Using Underscore

_.sortBy(collection, [iteratees=[_.identity]])

Creates an array of elements, sorted in ascending order by the results of running each element in a collection thru each iteratee. This method performs a stable sort, that is, it preserves the original sort order of equal elements. The iteratees are invoked with one argument: (value).

var objs = [

{ val1: 'abc',val2: 'a' },

{ val1: 'cde', val2: 'b' },

{ val1: 'fgh', val2: 'c' }

]; var sortedObjs = _.sortBy( objs, 'val1' );

2. Using ES6 sort function

var data = [

{ name: 'abc', value: 21 },

{ name: 'cde', value: 37 },

{ name: 'ee', value: 45 },

{ name: 'ff', value: -12 },

{ name: 'ab', value: 13 },

{ name: 'cs', value: 37 }

]; // sort by value

data.sort(function (a, b) {

return a.value - b.value;

});

3. Using Lodash

const sortedObjs = _.sortBy(data, 'string');

2. How to Round to at most 2 decimal places (only if necessary)

There are 3 different ways we can achieve this function.

Let’s understand some definitions before jumping to the solutions.

The parseFloat() function parses an argument (converting it to a string first if needed) and returns a floating point number. The toFixed() method formats a number using fixed-point notation.

Using ParseFloat

parseFloat("123.456").toFixed(2);

The Math.round() function returns the value of a number rounded to the nearest integer.

2. Using MathRound

Math.round( num * 100 + Number.EPSILON ) / 100

Number() Creates a new Number value.

3. Convert string to decimal

var str = 10.234.toFixed(2); // => '10.23'

var number = Number(str); // => 10.23

3. How do I loop through or enumerate a JavaScript Object?

Each ECMAScript version comp up with a different way to enumerate the Objects. Let’s check this out.

The Object.keys() method returns an array of a given object's own enumerable property names, iterated in the same order that a normal loop would. The forEach() method executes a provided function once for each array element.

Under ES5, you can combine Object.keys() and Array.prototype.forEach() :

var data = { val1: "abc", val2: "cde" }; Object.keys(data).forEach(function(key) {

console.log(key, obj[key]);

});

ES6 adds for...of :

The for...of statement creates a loop iterating over iterable objects, including: built-in String , Array , array-like objects (e.g., arguments or NodeList ), TypedArray , Map , Set , and user-defined iterables. It invokes a custom iteration hook with statements to be executed for the value of each distinct property of the object.

for (const key of Object.keys(data)) {

console.log(key, obj[key]);

}

ES8 adds Object.entries() which avoids having to look up each value in the original object:

The Object.entries() method returns an array of a given object's own enumerable string-keyed property [key, value] pairs, in the same order as that provided by a for...in loop.

Object.entries(data).forEach(

([key, value]) => console.log(key, value)

);

We can combine for...of , destructuring, and Object.entries :

for (const [key, value] of Object.entries(data)) {

console.log(key, value);

}

4. What is the difference between event.preventDefault() and return false

with return false, there is a chance that other functions are getting executed which is specifically written inside the click while preventDefault won’t allow executing anything.

$('a').click(function (e) {

// custom handling here // oops...runtime error...where oh where will the href take me? return false;

});

Example of preventDefault()

$('a').click(function (e) {

e.preventDefault(); // custom handling here // oops...runtime error, but at least the user isn't navigated away.

});

5. How can I check for an empty/undefined/null string in JavaScript?

if (!!data) {

// Some code here

}

Or use type casting:

if (Boolean(data)) {

// Code here

}

Both do the same function. Typecast the variable to Boolean, where str is a variable.

It returns false for null , undefined , 0 , 000 , "" , false .

It returns true for string "0" and whitespace " " .

6. How to insert an item into an array at a specific index (JavaScript)?

Append Single Element at a specific index

//Append at specific position(here at index 1)

array.splice(1, 0,'newData'); //Append at specific position (here at index 3)

array[3] = 'newData';

Append Multiple Element at a specific index

//Append from index number 1

array.splice(1, 0,'data1', 'data2', 'data3');

7. How to Get the current URL with JavaScript?

Use windows function: window.location.href

8. Checking if a key exists in a JavaScript object?

Using in operator

var data = "abc" in array;

Using hasOwnProperty

var result = data.hasOwnProperty("abc")

Accessing elements directly (brackets style)

var result = data["abc"] === undefined

Accessing elements directly (object style)

var result = array.abc === undefined;

9. How to merge two arrays in JavaScript and remove duplicate items?

We do play with arrays in day to day life and there are a lot of requirements where we need to combine arrays as well as need to remove duplicates.

Below are some approaches to achieve this.

1. Using Lodash

console.log(_.union([1, 2, 3], [101, 2, 1, 10], [2, 1]));

2. Using Filter and Concat

var a = [1, 2, 3], b = [101, 2, 1, 10]

var c = a.concat(b)

var d = c.filter((item, pos) => c.indexOf(item) === pos)

3. Using Set

[...new Set([...array1 ,...array2])]; // => remove duplication

10. How to check whether a string contains a substring in JavaScript?

We can use the following two methods to achieve this function.

1. includes

The includes() method determines whether an array includes a certain value among its entries, returning true or false as appropriate.

const val1 = "abcoo";

const val2 = "oo"; console.log(string.includes(val2));

2. index of

The indexOf() the method returns the first index at which a given element can be found in the array, or -1 if it is not present.

var string = "foo";

var substring = "oo"; console.log(string.indexOf(substring) !== -1);

If you are looking for array and object-related tips please check out this article.

11. How to replace all occurrences of a string?

We can use ES6 to handle this.

str = str.replace(/abc/g, '');

2. We can use Regex.

var find = 'abc';

var re = new RegExp(find, 'g'); str = str.replace(re, '');

we could simplify it even more:

function replaceAll(str, find, replace) {

return str.replace(new RegExp(find, 'g'), replace);

} function escapeRegExp(string) {

return string.replace(/[.*+\-?^${}()|[\]\\]/g, '\\$&'); // $& means the whole matched string

}

Which can be narrowed down to like this:

function replaceAll(str, find, replace) {

return str.replace(new RegExp(escapeRegExp(find), 'g'), replace);

}

12. How to correctly clone a JavaScript object?

Using ES6

var val1 = {data: "value"};

var val2= Object.assign({}, val1);

2. If you want a shallow copy

Object.assign({}, data)

3. For “deep” copy, use

JSON.parse(JSON.stringify(data))

13. What is the !! (not not) an operator in JavaScript?

!! converts the value to the right of it to its equivalent boolean value.

!!false === false

!!true === true !!0 === false

!!parseInt("foo") === false // NaN is falsy

!!1 === true

!!-1 === true // -1 is truthy

!!(1/0) === true // Infinity is truthy !!"" === false // empty string is falsy

!!"foo" === true // non-empty string is truthy

!!"false" === true // ...even if it contains a falsy value !!window.foo === false // undefined is falsy

!!null === false // null is falsy !!{} === true // an (empty) object is truthy

!![] === true // an (empty) array is truthy; PHP programmers beware!

14. How to Loop through an array in JavaScript

we have several options:

1. Sequential for loop:

var array = ["a","b"];

var arrayLength = array.length;

for (var i = 0; i < arrayLength; i++) {

console.log(array[i]);

//Do something

}

2. Array.prototype.forEach

The ES5 specification introduced a lot of beneficial array methods. One of them, the Array.prototype.forEach , gave us a concise way to iterate over an array:

const data = ["a", "b", "c"]

data.forEach(function (item, index) {

console.log(item, index);

});

3. Use of reduce:

const numbers = [1,2,3,4,5];

const sum = numbers.reduce((total, n) => total + n, 0); console.log(sum);

4. ES6 for-of statement

let data = ['a', 'b', 'c'];

for (const a of data){

console.log(a);

}

15. How do I copy to the clipboard in JavaScript?

We can prompt the user to click and enter by doing this:

function copy(text) {

window.prompt("Copy to clipboard: Ctrl+C, Enter", text);

}

Now the clipboard copy operation is SAFE because a user has clicked on the prompt.

<button id="data" onclick="copy(document.getElementById('data').innerHTML)">Copy here</button> <script>

function copyToClipboard(text) {

window.prompt("Copy to clipboard: Ctrl+C, Enter", text);

}

</script>

Recently, I was trying to prepare myself for the upcoming interviews and it was a bit tough to search in google and open link and see same questions each and every time so I thought of sharing what I have found and what is most common questions someone should know if they are preparing for an interview.

Below are the most common interview questions asked in Latest Angular Developer Interviews. These Angular Interview questions and answers help to prepare for Angular developer interviews from junior to senior levels. Moreover, this article covers the basics to advance angular interview questions which you must prepare in 2021.

16. How do I test for an empty JavaScript object?

There are several ways to achieve this function.

jQuery.isEmptyObject({}); // true

_.isEmpty({}); // true

_.isEmpty({}); // true

17. How do I make the first letter of a string uppercase in JavaScript?

We can either update the CSS which has text-transform property.

In CSS:

p:first-letter {

text-transform:capitalize;

}

2. Using function we can call toUpperCase() method.

function makeCapital(s)

{

return s && s[0].toUpperCase() + s.slice(1);

}

18. How can I change an element’s class with JavaScript?

There are lot of requirements where we need to change some color or css based on conditions.

How it can be done in the JavaScript?

To change all classes for an element:

To replace all existing classes with one or more new classes, set the className attribute:

document.getElementById("test").className = "newclass";

(We can use a space-delimited list to apply multiple classes.)

To add an additional class to an element:

To add a class to an element, without removing/affecting existing values, append a space and the new class name, like so:

document.getElementById("test").className += " newClass";

To remove a class from an element:

To remove a single class to an element, without affecting other potential classes, a simple regex replace is required:

document.getElementById("test").className =

document.getElementById("test").className.replace

( /(?:^|\s)newClass(?!\S)/g , '' )

19. Is it possible to apply CSS to half of a character?

We do see some fancy word art where the half of the character have different color while other half have different color. How we can achieve something like this in CSS?

Below is the example to make apply CSS for half character.

h1 {

display: inline-block;

margin: 0; /* for demo snippet */

line-height: 1em; /* for demo snippet */

font-family: helvetica, arial, sans-serif;

font-weight: bold;

font-size: 300px;

background: linear-gradient(to right, #7db9e8 50%,#1e5799 50%);

-webkit-background-clip: text;

-webkit-text-fill-color: transparent;

} <h1>X</h1>

20. How to append something to an array?

In older JavaScript version it was done by using the apply method.

The apply() method calls a function with a given this value, and arguments provided as an array (or an array-like object).

var array1 = [33, 45, 5];

var array2 = [100, 2]; Array.prototype.push.apply(array2, array1); console.log(array2); // [100, 2, 33, 45, 5]

With ES6 it can be done using the spread operator.

"use strict";

let array1 = [11, 42, 53];

let array2 = [1, 2]; array2.push(...array1); console.log(array2); // [11, 2, 3, 42, 53]

21. How to check if an object is an array?

When we would like to check that if the object is array or not we can follow below options.

var arr = [10,20,30,40,50];

Javascript (new and older browsers):

function isArray(arr) {

return arr.constructor.toString().indexOf("Array") > -1;

}

function isArray(arr) {

return arr instanceof Array;

}

function isArray(arr) {

return Object.prototype.toString.call(arr) === '[object Array]';

}

then call it like this:

isArray(arr);

JavaScript (IE9+, Ch5+, FF4+, Saf5+, Opera10.5+)

Array.isArray(arr);

Underscore and Lodash:

_.isArray(arr);

22. How to detect an undefined object property?

When we would like to check the specific property of object is undefined we can directly check using the if condition with === operator.

if(data.prop === undefined) {

alert("prop value is the special value `undefined`");

}

To check if an object does not actually have such a property, and will therefore return undefined by default when you try and access it:

if(!o.hasOwnProperty('prop')) {

alert("prop does not exist");

}

To check if the value associated with an identifier is the special value undefined , or if that identifier has not been declared. Note: this method is the only way of referring to an undeclared (note: different from having a value of undefined ) identifier without an early error:

if(typeof variable === 'undefined') {

alert('variable is either the special value `undefined`, or it has not been declared');

}

23. How can I convert a string to a boolean in JavaScript?

There are several methods to convert a string to a boolean in JavaScript.

Using the test method

var stringValue = "true";

var boolValue = (/true/i).test(stringValue) //returns true

Using comparison operator

var val = "true";

var boolValue = (val =="true"); //returns true

Using JSON.parse

var val = "true";

var boolValue = JSON.parse(val); //returns true

Using ternary operator

var val = “true”;

var boolValue = val.toLowerCase() == ‘true’ ? true : false; //returns true

Using switch-case

var val = "true";

var boolValue = getBoolean(val); //returns true

function getBoolean(value){

switch(value){

case true:

case "true":

case 1:

case "1":

case "on":

case "yes":

return true;

default:

return false;

}

}

24. How can I get query string values in JavaScript?

This is the most common usage when we deal with the URL parameters and want to extract the information from the URL.

Below are some methods from which we can get the string values.

ES2015 (ES6) : creating method to achieve this function

getQueryStringParams = query => {

return query

? (/^[?#]/.test(query) ? query.slice(1) : query)

.split('&')

.reduce((params, param) => {

let [key, value] = param.split('=');

params[key] = value ? decodeURIComponent(value.replace(/\+/g, ' ')) : '';

return params;

}, {}

)

: {}

};

URLSearchParams use inbuit method from location

You can use it on location :

let params = new URLSearchParams(location.search); let params = (new URL(location)).searchParams;

let url = new URL('https://abc.com?val1=1&val2=2');

let params = new URLSearchParams(url.search);

we can get params also using a shorthand .searchParams property on the URL object, like this:

let params = new URL('https://abc.com?val1=1&val2=2').searchParams;

params.get('val1'); // "1"

params.get('val2'); // "2"

25. How to get the length of a JavaScript object?

In most of the cases we do check the length of the array but what if want to check the length of objects? The following two methods are the best approaches to get the length of the Object.

1. Using Es6 feature

var size = Object.keys(data).length;

2. Using underscore

_.size({val1 : 1, val2 : 2, val3 : 3});

26. How to reverse a string that contains complicated emojis?

When we do more coding or attend some coding challenges, this is the most common question among them.

We can use lodash feature to achieve this challenge.

function reverse(txt) { return _.split(txt, '').reverse().join(''); } const data = 'abc abc👩‍🦰👩‍👩‍👦‍👦';

console.log(reverse(data));

27. How can I convert a string to an array of objects in JavaScript?

This type of scenario comes when we get some data from third-party APIs where we don’t have control. How we can convert a string to an array of objects to use in our application? Below is the easiest approach to achieve this result.

const

str = 'Option 1|false|Option 2|false|Option 3|false|Option 4|true',

data = []; for (let i = 0, a= str.split('|'); i < a.length; i += 2) {

const

option = a[i],

value = JSON.parse(a[i + 1]);

data.push({ option, value });

} console.log(data);

28. How to detect if the user changes tab in JavaScript?

This can be achieved by the latest event listener feature supported by JavaScript.

Below is the solution to handle the state of the tab.

document.addEventListener("visibilitychange", event => {

if (document.visibilityState == "visible") {

console.log("activated")

} else {

console.log("inactivated")

}

})

29. How to sum a property value from an array of objects?

When we have an array of objects which contain some number which we want to get sum below is the solution with reduce.

const data = [

{ val1: 'abc', val2: 50 },

{ val1: 'abc', val2: 50 },

{ val1: 'cde', val2: 75 },

{ val1: 'hji', val2: 35 },

{ val1: 'bbc', val2: 25 },

]; console.log(data.reduce((n, {val2}) => n + val2, 0))

30. How to Format JavaScript date?

When we come to formatting the date, it’s more headache as we do have different requirements according to the needs. How we can achieve everyone’s needs? Below are the most common methods used widely to format date in JavaScript.

1. You can use the native .toLocaleDateString()

Examples:

new Date().toLocaleDateString() // 8/19/2020 new Date().toLocaleDateString('en-US', {year: 'numeric', month: '2-digit', day: '2-digit'}); // 10/25/2020 (month and day with two digits) new Date().toLocaleDateString('en-ZA'); // 2020/10/25(year/month/day) notice the different locale new Date().toLocaleDateString('en-CA'); // 2020-10-25 (year-month-day) notice the different locale new Date().toLocaleString("en-US", {timeZone: "America/New_York"}); // 10/125/2020, 7:29:51 PM. (date and time in a specific timezone) new Date().toLocaleString("en-US", {hour: '2-digit', hour12: false, timeZone: "America/New_York"}); // 07 (just the hour)

2. We can use the moment.js

var now = new Date();

var dateString = moment(now).format('YYYY-MM-DD'); var dateStringWithTime = moment(now).format('YYYY-MM-DD HH:mm:ss'); <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"

31. How to Generate random string/characters in JavaScript?

There are a lot of times we need to send some random unique IDs to the backend. There are thousands of solutions to achieve this function but the following one I loved the most.

Generate a secure random alphanumeric Base-62 string:

function generateUID(length)

{

return window.btoa(Array.from(window.crypto.getRandomValues(new Uint8Array(length * 2))).map((b) => String.fromCharCode(b)).join("")).replace(/[+/]/g, "").substring(0, length);

} console.log(generateUID(22)); // "cFg3Upv2cE8cK8Xd7hHwWp"

console.log(generateUID(5)); // "CQGkP"

32. How to execute API calls after entering 3 characters in the field?

This is most commonly used when we want to search for a username or some value that already exists but to avoid call all the time we want to wait for the user to type certain characters before calling API.

This can be achieved using distinctUntilChanged And you can use the filter in the pipe

this.service.getData(data)

.pipe(

filter(_ => data.length === 3),

distinctUntilChanged()

).subscribe(rs => console.log(rs));

33. How to rename object keys inside an array?

Sometimes we need to change the keys to manipulate data. This is one of the efficient ways to rename the object keys inside an array.

You can use Object.values() to retrieve values and then array.reduce() to compose a new object:



prop_name: 'Negan',

prop_age: 45,

prop_weapon: 'Bat',

prop_email: '

prop_city: 'Washington'

},

{

prop_name: 'Daryl',

prop_age: 41,

prop_weapon: 'Crossbow',

prop_email: '

prop_city: 'Atlanta'

},

{

prop_name: 'Rick',

prop_age: 45,

prop_weapon: 'Magnum 357',

prop_email: '

prop_city: 'King County'

},

];

const newKeys = [

'firstname',

'age',

'weapon',

'email',

'city'

];

let result = customers.map(obj =>

Object.values(obj).reduce((acc, cur, i) => {

acc[newKeys[i]] = cur;

return acc;

}, {}));

console.log(result); const customers = [{prop_name: 'Negan',prop_age: 45,prop_weapon: 'Bat',prop_email: ' negan@sanctuary.com ',prop_city: 'Washington'},prop_name: 'Daryl',prop_age: 41,prop_weapon: 'Crossbow',prop_email: ' daryl.dixon@kickass.com ',prop_city: 'Atlanta'},prop_name: 'Rick',prop_age: 45,prop_weapon: 'Magnum 357',prop_email: ' rick@alexandria.com ',prop_city: 'King County'},];const newKeys = ['firstname','age','weapon','email','city'];let result = customers.map(obj =>Object.values(obj).reduce((acc, cur, i) => {acc[newKeys[i]] = cur;return acc;}, {}));console.log(result);

34. How do you clear the focus in javascript?

Focus… Focus… Yeah, this time we want to clear the focus from the specific element in the HTML. This can be achieved by the blur method.

if (document.activeElement instanceof HTMLElement)

document.activeElement.blur();

35. Binary to String in JavaScript

What if we have some binary code and we want to convert it into a string before using it in our code? It can be achieved using the fromCharCode method.

et binary = `1010011 1110100 1100001 1100011 1101011

1001111 1110110 1100101 1110010 1100110

1101100 1101111 1110111`; let outputStr = binary.split(' ') //Split string in array of binary chars

.map(bin => String.fromCharCode(parseInt(bin, 2))) //Map every binary char to real char

.join(''); //Join the array back to a string console.log(outputStr);

36. Shift strings Circular left and right in JavaScript

When we start practicing for the bigger companies this kind of javascript coding questions are common. Here is an example of shifting the string based on given values. It can be achieved using array slice methods.

function getShiftedString(s, leftShifts, rightShifts) {

// using `split('')` will result in certain unicode characters being separated incorrectly

// use Array.from instead:

const arr = Array.from(s);

const netLeftShifts = (leftShifts - rightShifts) % arr.length;

return [...arr.slice(netLeftShifts), ...arr.slice(0, netLeftShifts)]

.join('');

} console.log([

getShiftedString('abc', 0, 0),

getShiftedString('abc', 1, 0),

getShiftedString('abc', 0, 1),

getShiftedString('abc', 1, 1),

getShiftedString('123456789', 0, 0),

getShiftedString('123456789', 1, 5),

getShiftedString('123456789', 5, 1),

'----',

getShiftedString('123456789', 9, 0),

getShiftedString('123456789', 10, 0),

getShiftedString('123456789', 0, 9),

getShiftedString('123456789', 0, 10),

getShiftedString("🐎👱❤", 0, 0),

getShiftedString("🐎👱❤", 1, 0),

]);

37. Regular expression to check for IP addresses JavaScript

Regex help us to check any specific string and validate for us? What if we want regex for the IP address.

Here is the cleanest way to validate an IP Address, Let’s break it down:

Fact: a valid IP Address is has 4 octets , each octet can be a number between 0 - 255

Breakdown of Regex that matches any value between 0 - 255

25[0-5] matches 250 - 255

matches 2[0-4][0-9] matches 200 - 249

matches 1[0-9][0-9] matches 100 - 199

matches [1-9][0-9]? matches 1 - 99

matches 0 matches 0

const octet = '(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]?|0)';

Notes: When using new RegExp you should use \\. instead of \. since string will get escaped twice.

function isValidIP(str) {

const octet = '(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]?|0)';

const regex = new RegExp(`^${octet}\\.${octet}\\.${octet}\\.${octet}$`);

return regex.test(str);

}

38. How to JSON stringify a JavaScript Date and preserve timezone

When we want to store any specific date formatted value to the JSON. It can be achieved using this function.

var replacer = function(key, value) { if (this[key] instanceof Date) {

return this[key].toUTCString();

}



return value;

} console.log(JSON.stringify(new Date(), replacer));

console.log(JSON.stringify({ myProperty: new Date()}, replacer));

39. JavaScript to check if a string is a valid number

We have seen a lot of solution to check the number is valid or not but What if want to check if a string is a valid number or not?

Here is the best approach.

function isNumeric(n) {

return !isNaN(parseFloat(n)) && isFinite(n);

}

Below are some good test cases:

console.log(isNumeric(12345678912345678912)); // true

console.log(isNumeric('2 ')); // true

console.log(isNumeric('-32.2 ')); // true

console.log(isNumeric(-32.2)); // true

console.log(isNumeric(undefined)); // false // the accepted answer fails at these tests:

console.log(isNumeric('')); // false

console.log(isNumeric(null)); // false

console.log(isNumeric([])); // false

40. Export a JSON Object to a text file

When we want to export the JSON Object to a text file, below is the cleanest approach I found till this date.

const filename = 'data.json';

const jsonStr = JSON.stringify(JsonExport); let element = document.createElement('a');

element.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(jsonStr));

element.setAttribute('download', filename); element.style.display = 'none';

document.body.appendChild(element); element.click(); document.body.removeChild(element);

41. Wrap long template literal line to multiline without creating a new line in the string

If you introduce a line continuation ( \ ) at the point of the new line in the literal, it won't create a new line on output:

const text = `a very long string that just continues\

and continues and continues`;

console.log(text);

42. How to copy text from a div to clipboard

When we want to copy text from a div to clipboard below is the simplest approach I found during my development.

function CopyToClipboard(containerid) {

if (window.getSelection) {

if (window.getSelection().empty) { // Chrome

window.getSelection().empty();

} else if (window.getSelection().removeAllRanges) { // Firefox

window.getSelection().removeAllRanges();

}

} else if (document.selection) { // IE?

document.selection.empty();

} if (document.selection) {

var range = document.body.createTextRange();

range.moveToElementText(document.getElementById(containerid));

range.select().createTextRange();

document.execCommand("copy");

} else if (window.getSelection) {

var range = document.createRange();

range.selectNode(document.getElementById(containerid));

window.getSelection().addRange(range);

document.execCommand("copy");

}

}

References:

Are you preparing for interviews? Here are frequently asked interview questions in Angular. It covers the Latest interview questions for Angular and Frontend development. Let’s check how many of these questions you can answer?