Skip to content

Instantly share code, notes, and snippets.

@nepsilon
Last active March 23, 2019 18:09
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save nepsilon/066098f6b5be23cd39bdca6676aef323 to your computer and use it in GitHub Desktop.
Save nepsilon/066098f6b5be23cd39bdca6676aef323 to your computer and use it in GitHub Desktop.
5 handy Javascript one-liners — First published on fullweb.io issue #48

5 handy JavaScript one-liners

1. Generate a random string:

Math.random().toString(36).substr(2); 

This simply generates a random float, casts it into a String using base 36 and remove the 2 first chars 0 and. Note that this is not a replacement for UUID generation.

2. Clone an array:

var newA = myArray.slice(0); 

This will return a copy of the array, ensuring no other variables point to it.

3. Remove HTML tags:

"<b>A</b>".replace(/<[^>]+>/gi, ""); 

This is using a simple regular expression to remove any string that looks like <xxx> where x can be any char, including /.

4. Set a default value:

function foo(opts) {
  var options = opts || {};
} 

You will see this in any decent JS code. If opts is defined and not “binarily” false it will be assigned to options, otherwise it will assign an empty dictionary {}.

5. Reverse a string:

var str = "Pouet this string.";
str.split('').reverse().join('');
// Output: ".gnirts siht teuoP"
// Keep words order with:
str.split(' ').reverse().join(' ');
// Output: "string. this Pouet" 
// The first example splits on every character, reverses them and puts them back together.

The second splits only on words and joins them back separated by a space.

@nepsilon
Copy link
Author

Yes, I have put the word classes between quotes to mean that there are no classes per se in JavaScript.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment