JavaScript
Resources
#### notes ####
////
/* *******************************************************************************************
* GLOBAL OBJECTS > OBJECT
* https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object
* ******************************************************************************************* */
// Global object: properties
Object.length // length is a property of a function object, and indicates how many arguments the function expects, i.e. the number of formal parameters. This number does not include the rest parameter. Has a value of 1.
Object.prototype // Represents the Object prototype object and allows to add new properties and methods to all objects of type Object.
// Methods of the Object constructor
Object.assign(target, ...sources) // Copies the values of all enumerable own properties from one or more source objects to a target object. method is used to copy the values of all enumerable own properties from one or more source objects to a target object. It will return the target object
Object.create(MyObject) // Creates a new object with the specified prototype object and properties. The object which should be the prototype of the newly-created object.
Object.defineProperty(obj, prop, descriptor) // Adds the named property described by a given descriptor to an object.
Object.defineProperties(obj, props) // Adds the named properties described by the given descriptors to an object.
Object.entries(obj) // Returns an array containing all of the [key, value] pairs of a given object's own enumerable string properties.
Object.freeze(obj) // Freezes an object: other code can't delete or change any properties.
Object.getOwnPropertyDescriptor(obj, prop) // Returns a property descriptor for a named property on an object.
Object.getOwnPropertyDescriptors(obj) // Returns an object containing all own property descriptors for an object.
Object.getOwnPropertyNames(obj) // Returns an array containing the names of all of the given object's own enumerable and non-enumerable properties.
Object.getOwnPropertySymbols(obj) // Returns an array of all symbol properties found directly upon a given object.
Object.getPrototypeOf(obj) // Returns the prototype of the specified object.
Object.is(value1, value2); // Compares if two values are the same value. Equates all NaN values (which differs from both Abstract Equality Comparison and Strict Equality Comparison).
Object.isExtensible(obj) // Determines if extending of an object is allowed.
Object.isFrozen(obj) // Determines if an object was frozen.
Object.isSealed(obj) // Determines if an object is sealed.
Object.keys(obj) // Returns an array containing the names of all of the given object's own enumerable string properties.
Object.preventExtensions(obj) // Prevents any extensions of an object.
Object.seal(obj) // Prevents other code from deleting properties of an object.
Object.setPrototypeOf(obj, prototype) // Sets the prototype (i.e., the internal [[Prototype]] property).
Object.values(obj) // Returns an array containing the values that correspond to all of a given object's own enumerable string properties.
// Object instances and Object prototype object (Object.prototype.property or Object.prototype.method())
// Properties
obj.constructor // Specifies the function that creates an object's prototype.
obj.__proto__ // Points to the object which was used as prototype when the object was instantiated.
// Methods
obj.hasOwnProperty(prop) // Returns a boolean indicating whether an object contains the specified property as a direct property of that object and not inherited through the prototype chain.
prototypeObj.isPrototypeOf(object) // Returns a boolean indicating whether the object this method is called upon is in the prototype chain of the specified object.
obj.propertyIsEnumerable(prop) // Returns a boolean indicating if the internal ECMAScript [[Enumerable]] attribute is set.
obj.toLocaleString() // Calls toString().
obj.toString() // Returns a string representation of the object.
object.valueOf() // Returns the primitive value of the specified object.
/* *******************************************************************************************
* GLOBAL OBJECTS > ARRAY
* https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array
* ******************************************************************************************* */
// Global object: properties
Array.length // Reflects the number of elements in an array.
Array.prototype // Represents the prototype for the Array constructor and allows to add new properties and methods to all Array objects.
// Global object: methods
Array.from(arrayLike[, mapFn[, thisArg]]) // Creates a new Array instance from an array-like or iterable object.
Array.isArray(obj) // Returns true if a variable is an array, if not false.
Array.of(element0[, element1[, ...[, elementN]]]) // Creates a new Array instance with a variable number of arguments, regardless of number or type of the arguments.
// Instance: properties
arr.length // Reflects the number of elements in an array.
// Instance: mutator methods
arr.copyWithin(target, start, end) // Copies a sequence of array elements within the array.
arr.fill(value, start, end) // Fills all the elements of an array from a start index to an end index with a static value.
arr.pop() // Removes the last element from an array and returns that element.
arr.push([element1[, ...[, elementN]]]) // Adds one or more elements to the end of an array and returns the new length of the array.
arr.reverse() // Reverses the order of the elements of an array in place — the first becomes the last, and the last becomes the first.
arr.shift() // Removes the first element from an array and returns that element.
arr.sort() // Sorts the elements of an array in place and returns the array.
array.splice(start, deleteCount, item1, item2, ...) // Adds and/or removes elements from an array.
arr.unshift([element1[, ...[, elementN]]]) // Adds one or more elements to the front of an array and returns the new length of the array.
// Instance: accessor methods
arr.concat(value1[, value2[, ...[, valueN]]]) // Returns a new array comprised of this array joined with other array(s) and/or value(s).
arr.includes(searchElement, fromIndex) // Determines whether an array contains a certain element, returning true or false as appropriate.
arr.indexOf(searchElement[, fromIndex]) // Returns the first (least) index of an element within the array equal to the specified value, or -1 if none is found.
arr.join(separator) // Joins all elements of an array into a string.
arr.lastIndexOf(searchElement, fromIndex) // Returns the last (greatest) index of an element within the array equal to the specified value, or -1 if none is found.
arr.slice(begin, end) // Extracts a section of an array and returns a new array.
arr.toString() // Returns a string representing the array and its elements. Overrides the Object.prototype.toString() method.
arr.toLocaleString(locales, options) // Returns a localized string representing the array and its elements. Overrides the Object.prototype.toLocaleString() method.
// Instance: iteration methods
arr.entries() // Returns a new Array Iterator object that contains the key/value pairs for each index in the array.
arr.every(callback[, thisArg]) // Returns true if every element in this array satisfies the provided testing function.
arr.filter(callback[, thisArg]) // Creates a new array with all of the elements of this array for which the provided filtering function returns true.
arr.find(callback[, thisArg]) // Returns the found value in the array, if an element in the array satisfies the provided testing function or undefined if not found.
arr.findIndex(callback[, thisArg]) // Returns the found index in the array, if an element in the array satisfies the provided testing function or -1 if not found.
arr.forEach(callback[, thisArg]) // Calls a function for each element in the array.
arr.keys() // Returns a new Array Iterator that contains the keys for each index in the array.
arr.map(callback[, initialValue]) // Creates a new array with the results of calling a provided function on every element in this array.
arr.reduce(callback[, initialValue]) // Apply a function against an accumulator and each value of the array (from left-to-right) as to reduce it to a single value.
arr.reduceRight(callback[, initialValue]) // Apply a function against an accumulator and each value of the array (from right-to-left) as to reduce it to a single value.
arr.some(callback[, initialValue]) // Returns true if at least one element in this array satisfies the provided testing function.
arr.values() // Returns a new Array Iterator object that contains the values for each index in the array.
REF
Comments
// This is an in-line comment.
/* This is a
multi-line comment */
Data types
JavaScript provides seven different data types:
Data Types | Examples |
---|---|
undefined | A variable that has not been assigned a value is of type undefined . |
null | no value. |
string | 'a', 'aa', 'aaa', 'Hello!', '11 cats' |
number | 12, -1, 0.4 |
boolean | true, false |
object | A collection of properties. |
symbol | Represents a unique identifier. |
Variables
// declare a variable
var ourName;
// store values
myNumber = 5;
myString = "myVar";
// declare variables with the assignment operator
var myNum = 0;
// add, subtract, multiply and divide numbers
myVar = 5 + 10; // 15
myVar = 12 - 6; // 6
myVar = 13 * 13; // 169
myVar = 16 / 2; // 8
// increment and decrement numbers
i++; // the equivalent of i = i + 1
i--; // the equivalent of i = i - 1;
// decimals
var ourDecimal = 5.7; // float
ES6 var, let and const
- Unlike
var
,let
throws an error if you declare the same variable twice. - Variables declared with
let
inside a block, statement, or expression, its scope is limited to that block, statement, or expression. - Variables declared with
const
are read-only and cannot be reassigned. - Objects (including arrays and functions) assigned to a variable using
const
are still mutable and only prevents the reassignment of the variable identifier.
To ensure your data doesn't change, JavaScript provides a function Object.freeze to prevent data mutation.
let obj = {
name: "FreeCodeCamp",
review: "Awesome"
};
Object.freeze(obj);
obj.review = "bad"; //will be ignored. Mutation not allowed
obj.newProp = "Test"; // will be ignored. Mutation not allowed
console.log(obj);
// { name: "FreeCodeCamp", review:"Awesome"}
Strings
Basics
// escape literal quotes
var sampleStr = 'Alan said, "Peter is learning JavaScript".';
// this prints: Alan said, "Peter is learning JavaScript".
// concatenating strings
var ourStr = "I come first. " + "I come second.";
// concatenating strings with +=
var ourStr = "I come first. ";
ourStr += "I come second.";
// constructing strings with variables
var ourName = "freeCodeCamp";
var ourStr = "Hello, our name is " + ourName + ", how are you?";
// appending variables to strings
var anAdjective = "awesome!";
var ourStr = "freeCodeCamp is ";
ourStr += anAdjective;
Escape sequences
Code | Output |
---|---|
\' | single quote (' ) |
\" | double quote (" ) |
\\ | backslash (\ ) |
\n | newline |
\r | carriage return |
\t | tab |
\b | backspace |
\f | form feed |
The length of a string
"Alan Peter".length; // 10
Split and Join
let str = 'a string';
let splittedStr = str.split('');
// [ 'a', ' ', 's', 't', 'r', 'i', 'n', 'g' ]
let joinedStr = splittedStr.join('')
// a string
Index of a String
//first element has an index of 0
var firstLetterOfFirstName = "";
var firstName = "Ada";
firstLetterOfFirstName = firstName[0]; // A
// find the las character of a string
var firstName = "Ada";
var lastLetterOfFirstName = firstName[firstName.length - 1]; // a
ES6 Template Literals
const person = {
name: "Zodiac Hasbro",
age: 56
};
// Template literal with multi-line and string interpolation
const greeting = `Hello, my name is ${person.name}!
I am ${person.age} years old.`;
console.log(greeting);
// Hello, my name is Zodiac Hasbro!
// I am 56 years old.
Arrays
var sandwich = ["peanut butter", "jelly", "bread"][
// nested arrays
(["Bulls", 23], ["White Sox", 45])
];
Index of an array
var ourArray = [50, 60, 70];
var ourData = ourArray[0]; // equals 50
// modify an array with indexes
var ourArray = [50, 40, 30];
ourArray[0] = 15; // equals [15,40,30]
// access multi-dimensional arrays with indexes
var arr = [[1, 2, 3], [4, 5, 6], [7, 8, 9], [[10, 11, 12], 13, 14]];
arr[3]; // [[10,11,12], 13, 14]
arr[3][0]; // [10,11,12]
arr[3][0][1]; // 11
Manipulate arrays with reverse, push, pop, shift and unshift
// reverse an array
[1, 'two', 3].reverse() // [ 3, 'two', 1 ]
// push() to append data to the end of an array
var arr = [1, 2, 3];
arr.push(4); // arr is now [1,2,3,4]
// pop() to "pop" a value off of the end of an array
var threeArr = [1, 4, 6];
var oneDown = threeArr.pop();
console.log(oneDown); // Returns 6
console.log(threeArr); // Returns [1, 4]
// shift() removes the first element of an array
var ourArray = [1, 2, [3]];
var removedFromOurArray = ourArray.shift();
// removedFromOurArray now equals 1 and ourArray now equals [2, [3]].
// unshift() adds the element at the beginning of the array
var ourArray = ["Stimpson", "J", "cat"];
ourArray.shift(); // ourArray now equals ["J", "cat"]
ourArray.unshift("Happy"); // ourArray now equals ["Happy", "J", "cat"]
Remove any element with splice
// first parameter is the index, the second indicates the number of elements to delete.
let array = ['today', 'was', 'not', 'so', 'great'];
array.splice(2, 2);
// remove 2 elements beginning with the 3rd element
// array now equals ['today', 'was', 'great']
// also returns a new array containing the value of the removed elements
let array = ['I', 'am', 'feeling', 'really', 'happy'];
let newArray = array.splice(3, 2);
// newArray equals ['really', 'happy']
// the third parameter, represents one or more elements, let us add them
function colorChange(arr, index, newColor) {
arr.splice(index, 1, newColor);
return arr;
}
let colorScheme = ['#878787', '#a08794', '#bb7e8c', '#c9b6be', '#d1becf'];
colorScheme = colorChange(colorScheme, 2, '#332327');
// we have removed '#bb7e8c' and added '#332327' in its place
// colorScheme now equals ['#878787', '#a08794', '#332327', '#c9b6be', '#d1becf']
Copy an array with slice
// Copies a given number of elements to a new array and leaves the original array untouched
let weatherConditions = ['rain', 'snow', 'sleet', 'hail', 'clear'];
let todaysWeather = weatherConditions.slice(1, 3);
// todaysWeather equals ['snow', 'sleet'];
// weatherConditions still equals ['rain', 'snow', 'sleet', 'hail', 'clear']
indexOf
let fruits = ['apples', 'pears', 'oranges', 'peaches', 'pears'];
fruits.indexOf('dates') // -1
fruits.indexOf('oranges') // 2
fruits.indexOf('pears') // 1, the first index at which the element exists
Accessing Nested Arrays
var ourPets = [
{
animalType: "cat",
names: ["Meowzer", "Fluffy", "Kit-Cat"]
},
{
animalType: "dog",
names: ["Spot", "Bowser", "Frankie"]
}
];
ourPets[0].names[1]; // "Fluffy"
ourPets[1].names[0]; // "Spot"
ES6 Includes to Determine if an Array Contains an Element
let fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.includes("Mango"); // true
ES6 The Spread Operator
// The ES5 code below uses apply() to compute the maximum value in an array.
var arr = [6, 89, 3, 45];
var maximus = Math.max.apply(null, arr); // 89
// ...arr returns an unpacked array. In other words, it spreads the array.
const arr = [6, 89, 3, 45];
const maximus = Math.max(...arr); // 89
// [...new Set(arr)] = unique value array
const arr = [1,2,2,3,3,4,5,5];
const uniq = [...new Set(arr)]; // [1,2,3,4,5]
// copy an array
let thisArray = [true, true, undefined, false, null];
let thatArray = [...thisArray];
// thatArray equals [true, true, undefined, false, null]
// thisArray remains unchanged, and is identical to thatArray
// combine arrays
let thisArray = ['sage', 'rosemary', 'parsley', 'thyme'];
let thatArray = ['basil', 'cilantro', ...thisArray, 'coriander'];
// thatArray now equals ['basil', 'cilantro', 'sage', 'rosemary', 'parsley', 'thyme', 'coriander']
ES6 Destructuring Arrays to Assign Variables
const [a, b] = [1, 2, 3, 4, 5, 6];
console.log(a, b); // 1, 2
// it can access any value by using commas to reach the desired index
const [a, b, , , c] = [1, 2, 3, 4, 5, 6];
console.log(a, b, c); // 1, 2, 5
// to collect the rest of the elements into a separate array.
const [a, b, ...arr] = [1, 2, 3, 4, 5, 7];
console.log(a, b); // 1, 2
console.log(arr); // [3, 4, 5, 7]
JavaScript Objects
var cat = {
name: "Whiskers",
legs: 4,
tails: 1,
enemies: ["Water", "Dogs"]
};
Accessing Objects Properties
Accessing with dot (.
) notation
var myObj = {
prop1: "val1",
prop2: "val2"
};
var prop1val = myObj.prop1; // val1
var prop2val = myObj.prop2; // val2
Accessing with bracket ([]
) notation
var myObj = {
"Space Name": "Kirk",
"More Space": "Spock",
NoSpace: "USS Enterprise"
};
myObj["Space Name"]; // Kirk
myObj["More Space"]; // Spock
myObj["NoSpace"]; // USS Enterprise
Accessing with variables
var dogs = {
Fido: "Mutt",
Hunter: "Doberman",
Snoopie: "Beagle"
};
var myDog = "Hunter";
var myBreed = dogs[myDog];
console.log(myBreed); // "Doberman"
Accessing and modifying Nested Objects
let userActivity = {
id: 23894201352,
date: 'January 1, 2017',
data: {
totalUsers: 51,
online: 42
}
};
userActivity.data.online = 45; // or
userActivity['data'].online = 45; // or
userActivity['data']['online'] = 45;
Creating an array from the keys of an object
let users = {
Alan: {
age: 27,
online: false
},
Jeff: {
age: 32,
online: true
},
Sarah: {
age: 48,
online: false
},
Ryan: {
age: 19,
online: true
}
};
function getArrayOfUsers(obj) {
let arr = [];
for (let key in obj) {
arr.push(key)
}
return arr;
}
Modifying Objects Properties
// Updating object properties
var ourDog = {
name: "Camper",
legs: 4,
tails: 1,
friends: ["everything!"]
};
ourDog.name = "Happy Camper"; // or
ourDog["name"] = "Happy Camper";
// add new properties
ourDog.bark = "bow-wow"; // or
ourDog["bark"] = "bow-wow";
// delete properties
delete ourDog.bark;
Objects for Lookups
var alpha = {
1:"Z",
2:"Y",
3:"X",
4:"W",
...
24:"C",
25:"B",
26:"A"
};
alpha[2]; // "Y"
alpha[24]; // "C"
var value = 2;
alpha[value]; // "Y"
Test Object Properties
var myObj = {
top: "hat",
bottom: "pants"
};
myObj.hasOwnProperty("top"); // true
myObj.hasOwnProperty("middle"); // false
Accessing Nested Objects
var ourStorage = {
desk: {
drawer: "stapler"
},
cabinet: {
"top drawer": {
folder1: "a file",
folder2: "secrets"
},
"bottom drawer": "soda"
}
};
ourStorage.cabinet["top drawer"].folder2; // "secrets"
ourStorage.desk.drawer; // "stapler"
ES6 Destructuring Variables from Objects
// Consider the following ES5 code
var voxel = { x: 3.6, y: 7.4, z: 6.54 };
var x = voxel.x; // x = 3.6
var y = voxel.y; // y = 7.4
var z = voxel.z; // z = 6.54
// the same assignment statement with ES6 destructuring syntax
const { x, y, z } = voxel; // x = 3.6, y = 7.4, z = 6.54
// to store the values of voxel.x into a, voxel.y into b, and voxel.z into c, you have that freedom as well
const { x: a, y: b, z: c } = voxel; // a = 3.6, b = 7.4, c = 6.54
// Destructuring Variables from Nested Objects
const a = {
start: { x: 5, y: 6 },
end: { x: 6, y: -9 }
};
const {
start: { x: startX, y: startY }
} = a;
console.log(startX, startY); // 5, 6
ES6 Destructuring to Pass an Object as a Function's Parameters
// destructure the object in a function argument itself.
const profileUpdate = profileData => {
const { name, age, nationality, location } = profileData;
// do something with these variables
};
// this can also be done in-place:
const profileUpdate = ({ name, age, nationality, location }) => {
/* do something with these fields */
};
ES6 Object Literal Declarations Using Simple Fields
const getMousePosition = (x, y) => ({
x: x,
y: y
});
// the same function rewritten to use this new syntax:
const getMousePosition = (x, y) => ({ x, y });
Booleans
Booleans may only be one of two values: true or false. They are basically little on-off switches, where true is "on" and false is "off". These two states are mutually exclusive.
true;
false;
If Else Statements
if (condition is true) {
statement is executed
}
Else Statement
if (num > 10) {
return "Bigger than 10";
} else {
return "10 or Less";
}
Else if statement
if (num > 15) {
return "Bigger than 15";
} else if (num < 5) {
return "Smaller than 5";
} else {
return "Between 5 and 15";
}
Conditional (Ternary) Operator
// this if statement...
function findGreater(a, b) {
if (a > b) {
return "a is greater";
} else {
return "b is greater";
}
}
// is equivalent to this ternary operator
function findGreater(a, b) {
return a > b ? "a is greater" : "b is greater";
}
Multiple Conditional (Ternary) Operators
// this if statement...
function findGreaterOrEqual(a, b) {
if (a === b) {
return "a and b are equal";
} else if (a > b) {
return "a is greater";
} else {
return "b is greater";
}
}
// is equivalent to this ternary operator
function findGreaterOrEqual(a, b) {
return a === b
? "a and b are equal"
: a > b
? "a is greater"
: "b is greater";
}
Switch Statement
switch(num) {
case value1:
statement1;
break;
case value2:
statement2;
break;
...
case valueN:
statementN;
break;
}
Default Switch Statement
switch (num) {
case value1:
statement1;
break;
case value2:
statement2;
break;
...
default:
defaultStatement;
break;
}
Multiple Options with Switch Statement
switch (val) {
case 1:
case 2:
case 3:
result = "1, 2, or 3";
break;
case 4:
result = "4 alone";
}
Comparison Operators
Operator | Meaning |
---|---|
== | Equality |
=== | Strict Equality |
!= | Inequality |
!== | Strict Inequality |
> | Greater Than |
>= | Greater or Equal Than |
< | Less Than |
<= | Less or Equal Than |
&& | And |
` |
While Loops
var ourArray = [];
var i = 0;
while (i < 5) {
ourArray.push(i);
i++;
}
Do...While Loops
var ourArray = [];
var i = 0;
do {
ourArray.push(i);
i++;
} while (i < 5);
For Loops
var ourArray = [];
var i = 0;
while (i < 5) {
ourArray.push(i);
i++;
}
// Count Backwards With a For Loop
var ourArray = [];
for (var i = 10; i > 0; i -= 2) {
ourArray.push(i);
}
// Iterate Through an Array
var arr = [10, 9, 8, 7, 6];
for (var i = 0; i < arr.length; i++) {
console.log(arr[i]);
}
// Nested for loops
var arr = [[1, 2], [3, 4], [5, 6]];
for (var i = 0; i < arr.length; i++) {
for (var j = 0; j < arr[i].length; j++) {
console.log(arr[i][j]);
}
}
ES6 for-of
for (let value of myArray) {
console.log(value);
}
Functions
function functionName() {
console.log("Hello World");
}
functionName(); // call the function
Function Arguments
function ourFunctionWithArgs(a, b) {
console.log(a - b);
}
ourFunctionWithArgs(10, 5); // 5
Return Statement
function plusThree(num) {
return num + 3;
}
var answer = plusThree(5); // 8
Immediately Invoked Function Expression or IIFE
(function () {
console.log("A cozy nest is ready");
})()
ES6 Arrow Functions
const myFunc = function() {
const myVar = "value";
return myVar;
};
// can be rewritten like this
const myFunc = () => {
const myVar = "value";
return myVar;
};
// and if there is no function body, and only a return value
const myFunc = () => "value";
// to pass parameters to an arrow function
const doubler = item => item * 2;
ES6 Higher Order Arrow Functions
FBPosts.filter(function(post) {
return post.thumbnail !== null && post.shares > 100 && post.likes > 500;
});
// the previous function can be rewritten like this
FBPosts.filter(
post => post.thumbnail !== null && post.shares > 100 && post.likes > 500
);
ES6 Rest Operator with Function Parameters
With the rest operator, you can create functions that take a variable number of arguments. These arguments are stored in an array that can be accessed later from inside the function.
function howMany(...args) {
return "You have passed " + args.length + " arguments.";
}
console.log(howMany(0, 1, 2)); // You have passed 3 arguments
console.log(howMany("string", null, [1, 2, 3], {})); // You have passed 4 arguments.
ES6 Declarative Functions within Objects
// When defining functions within objects in ES5, we have to use the keyword function
const person = {
name: "Taylor",
sayHello: function() {
return `Hello! My name is ${this.name}.`;
}
};
// With ES6, You can remove the function keyword and colon
const person = {
name: "Taylor",
sayHello() {
return `Hello! My name is ${this.name}.`;
}
};
Regular Expressions
Character | Description |
---|---|
\ | Escapes a special character. |
` | ` |
i | This flag is used to ignore upper and lowercase. /ignorecase/i . |
g | Search or extract a pattern more than once. |
. | The wildcard character . will match any character except new lines. |
[] | Allow you to define the characters to match. /b[au]g/ will match "bag", "bug" but not "bog". |
[a-z] | Match all the characters between a and z. |
[1-9] | Match all the numbers between 1 and 9. |
[a-z1-9] | Match all the character between a and z, and the numbers between 1 and 9. |
[^] | Match the characters not in the set. [^a-e] match all other characters except A, B, C, D, and E. |
+ | Match 1 or more occurrences of the previous character in a row. |
* | Match 0 or more occurrences of the previous character. |
? | Match 0 or 1 occurrence of the previous character. Useful for Lazy matching. |
^ | Search for patterns at the beginning of strings. |
$ | Search for patterns at the end of a string. |
\w | Equal to [A-Za-z0-9_] . Matches upper, lowercase, numbers the and underscore character (-). |
\W | Matches any nonword character. Equivalent to [^a-za-z0-9_] . |
\d | Equal to [0-9] . Match one digit. |
\D | Equal to [^0-9] . Match one non digit. |
\s | Match a whitespace. |
\S | Match everything except whitespace. |
a{2,5} | Match the letter a between 3 and 5 times. |
a{2,} | Specify only the lower number of matches. |
a{5} | Specify the exact number of matches. |
(...) | Specify a group that can be acceded with number (from 1) |