5 Useful JavaScript hacks&tricks

Today I want to share with you some JavaScript examples that you might find useful in your everyday work. All of the examples have live working demos so you can easy try and edit according to your needs. So, here is my Top 5 for today…


1. Limit which characters you can enter in your text field

Sometimes there is a need to limit the allowed characters that can be entered by users in the input fields. This could be also achieved with using keydown and keycode, but in this example we are using on.(“input”).

$("input[type='text']").on("input", function(){
  // regex of the allowed chars in the text field
  var regexp = /[^a-zA-Z0-9#\.,:-_\[\]#~@+\/\?€]/g;
  $(this).val( $(this).val().replace(regexp,'') );

What’s this code privilege?

  • It works on mobile browsers (keydown and keycode have problem).
  • It works on AJAX generated content too, because We’re using “on”.
  • Better performance than keydown, for example on paste event.

Try the working example code: https://jsfiddle.net/n6udj5fv/6

2. Copy to clipboard

For this example we are using execCommand(‘copy’) that will copy the selected content into clipboard.

// Copy to clipboard example
document.querySelector("#copy-button").onclick = function() {
 // Select the content
 // Copy to the clipboard

Try the working example code: https://jsfiddle.net/u97gh09d/3/

3. Remove duplicate elements from an array of primitives

In this example I’ll demonstrate two ways of achieving this.

Example 1: With using filter and index of element

var arrayWithoutDuplicates = arrayWithDuplicates.filter( (el, i, arr) => arr.indexOf(el) === i);
console.log('Array before duplicate removal: ' + arrayWithDuplicates);
console.log('Array after duplicate removal: ' + arrayWithoutDuplicates);

Example 2: With using Set and Array’s from method

arrayWithoutDuplicates = Array.from( new Set(arrayWithDuplicates) );
console.log('Array before duplicate removal: ' + arrayWithDuplicates);
console.log('Array after duplicate removal: ' + arrayWithoutDuplicates);

Try the working example code: https://jsfiddle.net/no3f5bLe/2/

(Source: http://www.jstips.co/en/deduplicate-an-array/)

4. Remove duplicate elements from an array of Objects

We need to use a different approach when filtering array of Objects because Objects are stored by reference and primitives are stored by value. That is why we are using a hash table to get the same result.

function RemoveDuplicateObjects(arr) {
 var hashTable = {};

 return arr.filter(function (el) {
 var key = JSON.stringify(el);
 var match = Boolean(hashTable[key]);

 return (match ? false : hashTable[key] = true);

Try the working example code: https://jsfiddle.net/pf9rgy6p/3/ 

(Source: http://www.jstips.co/en/deduplicate-an-array/)

5. Using !! operator to convert values to boolean

In cases when we want to check if some variable exists or has a valid value it’s useful to know how to use the !! operator (double negation operator). This operator will return false if the variable has value of 0, “”, Nan, undefined or null, it will return true in any other case.

var UserAccount1 = {};
var UserAccount2 = {};

UserAccount1.Balance = 0;
UserAccount1.HasMoney = !!UserAccount1.Balance;

UserAccount2.Balance = 1450;
UserAccount2.HasMoney = !!UserAccount2.Balance;

console.log('User 1 has Money!');

console.log('User 2 has Money!');


Try the working example code:  https://jsfiddle.net/avwbbea1/1/ 

Hope you find this examples very useful!

Happy codding!



Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s