Skip to content

Instantly share code, notes, and snippets.

> var first_name = function (name) {
... return name;
... }
undefined
> first_name("bob");
'bob'
//first_name is a variable with an anonymous function as its value. we assign
> function add(x,y) {
var yeti = {
find: function fn() {
return this.appetite;
},
appetite: "gigantic"
};
var polar_bear = Object.create(yeti);
polar_bear.appetite = "huge";
var yeti = {
find: function fn() {
return this.appetite;
},
appetite: "gigantic"
};
var polar_bear = Object.create(yeti);
polar_bear.appetite = "huge";
var seal = Object.create(polar_bear);
seal.appetite = "big";
var arctic_hare = Object.create(seal);
var snow_mouse = Object.create(arctic_hare);
var yao = {
self: function () { return this }
}
console.log(yao === yao.self());
//yao.self is equal to yao, so this return a boolean value of true.
> var lebron = {
... occupation: "basketball",
... introduction: function () {
@Chryus
Chryus / gist:8616950
Created January 25, 2014 14:10
The + character will make your regex greedy. The ? character will make your regex lazy.
//the plus character is greedy. It matches the preceding character as many times as possible.
str = "maroooooooooned on a desert island"
reg = /(o+)/
res = str.match(reg); //=> 'ooooooooo'
//we can make the plus operator lazy by adding a question mark after it.
//note that the only thing changed is the insertion of the special character "?", which tells the RegEx plus operator to calm down and not be such a glutton for o's.
str = "maroooooooooned on a desert island"
> var reg = /([a-zA-Z\s]+) ([A-Z]{2})/
> var string = "New York NY 10006 United States"
> var res = string.replace(reg, '$1,');
> console.log(res);
New York, 10006 United States
> var reg = /([a-zA-Z\s]+) ([A-Z]{2})/
> var string = "New York NY 10006 United States"
> var res = string.match(reg);
> console.log(res);
[ 'New York NY',
'New York',
> var reg = /([a-zA-Z\s]+) ([A-Z]{2})/g
> var string = "New York NY 10006 United States"
> var res = string.match(reg);
> console.log(res);
[ 'New York NY' ]
@Chryus
Chryus / gist:8843341
Last active August 29, 2015 13:56
An example that uses lookarounds in Javascript to validate a password. Example from https://www.codewars.com/.
function validate(password) {
return /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])[0-9a-zA-z]{6,}$/.test(password);
}
//If password contains at least one digit, one uppercase char, one lowercase char PLUS six or more
//chars from the character class composed of one digit, one uppercase char, and one lowercase char.
> validate('djI38D55');
true
//passes if 6 or more chars