JavaScript Regular Expressions

JavaScript Regular Expressions
❮ Previous Next ❯
A regular expression is a sequence of characters that forms a search pattern.

The search pattern can be used for text search and text replace operations.

What Is a Regular Expression?
A regular expression is a sequence of characters that forms a search pattern.

When you search for data in a text, you can use this search pattern to describe what you are searching for.

A regular expression can be a single character, or a more complicated pattern.

Regular expressions can be used to perform all types of text search and text replace operations.

Syntax
/pattern/modifiers;
Example
var patt = /Omegas/i;
Example explained:

/Omegas/i  is a regular expression.

Omegas  is a pattern (to be used in a search).

i  is a modifier (modifies the search to be case-insensitive).

Using String Methods
In JavaScript, regular expressions are often used with the two string methods: search() and replace().

The search() method uses an expression to search for a match, and returns the position of the match.

The replace() method returns a modified string where the pattern is replaced.

Using String search() With a Regular Expression
Example
Use a regular expression to do a case-insensitive search for “Omegas” in a string:

var str = “Visit Omegas”;
var n = str.search(/Omegas/i);
The result in n will be:

6
»
Using String search() With String
The search method will also accept a string as search argument. The string argument will be converted to a regular expression:

Example
Use a string to do a search for “Omegas” in a string:

var str = “Visit Omegas!”;
var n = str.search(“Omegas”);
»
Use String replace() With a Regular Expression
Example
Use a case insensitive regular expression to replace Microsoft with Omegas in a string:

var str = “Visit Microsoft!”;
var res = str.replace(/microsoft/i, “Omegas”);
The result in res will be:

Visit Omegas!
»
Using String replace() With a String
The replace() method will also accept a string as search argument:

var str = “Visit Microsoft!”;
var res = str.replace(“Microsoft”, “Omegas”);
»
Did You Notice?
Regular expression arguments (instead of string arguments) can be used in the methods above.
Regular expressions can make your search much more powerful (case insensitive for example).

Regular Expression Modifiers
Modifiers can be used to perform case-insensitive more global searches:

Modifier Description
i Perform case-insensitive matching
g Perform a global match (find all matches rather than stopping after the first match)
m Perform multiline matching
Regular Expression Patterns
Brackets are used to find a range of characters:

Expression Description
[abc] Find any of the characters between the brackets
[0-9] Find any of the digits between the brackets
(x|y) Find any of the alternatives separated with |
Metacharacters are characters with a special meaning:

Metacharacter Description
\d Find a digit
\s Find a whitespace character
\b Find a match at the beginning or at the end of a word
\uxxxx Find the Unicode character specified by the hexadecimal number xxxx
Quantifiers define quantities:

Quantifier Description
n+ Matches any string that contains at least one n
n* Matches any string that contains zero or more occurrences of n
n? Matches any string that contains zero or one occurrences of n
Using the RegExp Object
In JavaScript, the RegExp object is a regular expression object with predefined properties and methods.

Using test()
The test() method is a RegExp expression method.

It searches a string for a pattern, and returns true or false, depending on the result.

The following example searches a string for the character “e”:

Example
var patt = /e/;
patt.test(“The best things in life are free!”);
Since there is an “e” in the string, the output of the code above will be:

true
»
You don’t have to put the regular expression in a variable first. The two lines above can be shortened to one:

/e/.test(“The best things in life are free!”);
Using exec()
The exec() method is a RegExp expression method.

It searches a string for a specified pattern, and returns the found text.

If no match is found, it returns null.

The following example searches a string for the character “e”:

Example 1
/e/.exec(“The best things in life are free!”);
Since there is an “e” in the string, the output of the code above will be:

e
»
Complete RegExp Reference
For a complete reference, go to our Complete JavaScript RegExp Reference.

The reference contains descriptions and examples of all RegExp properties and methods.

❮ Previous Next ❯

JavaScript Errors – Throw and Try to Catch

TUTORIAL HOME
JavaScript Errors – Throw and Try to Catch
❮ Previous Next ❯
The try statement lets you test a block of code for errors.

The catch statement lets you handle the error.

The throw statement lets you create custom errors.

The finally statement lets you execute code, after try and catch, regardless of the result.

Errors Will Happen!
When executing JavaScript code, different errors can occur.

Errors can be coding errors made by the programmer, errors due to wrong input, and other unforeseeable things.

Example
In this example we have written alert as adddlert to deliberately produce an error:

try {
    adddlert(“Welcome guest!”);
}
catch(err) {
    document.getElementById(“demo”).innerHTML = err.message;
}

»
JavaScript catches adddlert as an error, and executes the catch code to handle it.

JavaScript try and catch
The try statement allows you to define a block of code to be tested for errors while it is being executed.

The catch statement allows you to define a block of code to be executed, if an error occurs in the try block.

The JavaScript statements try and catch come in pairs:

try {
    Block of code to try
}
catch(err) {
    Block of code to handle errors
}
JavaScript Throws Errors
When an error occurs, JavaScript will normally stop and generate an error message.

The technical term for this is: JavaScript will  throw an exception (throw an error).

JavaScript will actually create an Error object with two properties: name and message.

The throw Statement
The throw statement allows you to create a custom error.

Technically you can throw an exception (throw an error).

The exception can be a JavaScript String, a Number, a Boolean or an Object:

throw “Too big”;    // throw a text
throw 500;          // throw a number
If you use throw together with try and catch, you can control program flow and generate custom error messages.

Input Validation Example
This example examines input. If the value is wrong, an exception (err) is thrown.

The exception (err) is caught by the catch statement and a custom error message is displayed:

Please input a number between 5 and 10:

Test Input

function myFunction() {
    var message, x;
    message = document.getElementById(“message”);
    message.innerHTML = “”;
    x = document.getElementById(“demo”).value;
    try {
        if(x == “”) throw “empty”;
        if(isNaN(x)) throw “not a number”;
        x = Number(x);
        if(x < 5) throw "too low";
        if(x > 10) throw “too high”;
    }
    catch(err) {
        message.innerHTML = “Input is ” + err;
    }
}

»
HTML Validation
The code above is just an example.

Modern browsers will often use a combination of JavaScript and built-in HTML validation, using predefined validation rules defined in HTML attributes:

<input id="demo" type="number" min="5" max="10" step="1"
You can read more about forms validation in a later chapter of this tutorial.

The finally Statement
The finally statement lets you execute code, after try and catch, regardless of the result:

try {
    Block of code to try
}
catch(err) {
    Block of code to handle errors
}
finally {
    Block of code to be executed regardless of the try / catch result
}
Example
function myFunction() {
    var message, x;
    message = document.getElementById(“message”);
    message.innerHTML = “”;
    x = document.getElementById(“demo”).value;
    try {
        if(x == “”) throw “is empty”;
        if(isNaN(x)) throw “is not a number”;
        x = Number(x);
        if(x > 10) throw “is too high”;
        if(x < 5) throw "is too low";
    }
    catch(err) {
        message.innerHTML = “Error: ” + err + “.”;
    }
    finally {
        document.getElementById(“demo”).value = “”;
    }
}
»
The Error Object
JavaScript has a built in error object that provides error information when an error occurs.

The error object provides two useful properties: name and message.

Error Object Properties
Property Description
name Sets or returns an error name
message Sets or returns an error message (a string)
Error Name Values
Six different values can be returned by the error name property:

Error Name Description
EvalError An error has occurred in the eval() function
RangeError A number “out of range” has occurred
ReferenceError An illegal reference has occurred
SyntaxError A syntax error has occurred
TypeError A type error has occurred
URIError An error in encodeURI() has occurred
The six different values are described below.

Eval Error
An EvalError indicates an error in the eval() function.

Newer versions of JavaScript does not throw any EvalError. Use SyntaxError instead.

Range Error
A RangeError is thrown if you use a number that is outside the range of legal values.

For example: You cannot set the number of significant digits of a number to 500.

Example
var num = 1;
try {
    num.toPrecision(500);   // A number cannot have 500 significant digits
}
catch(err) {
    document.getElementById(“demo”).innerHTML = err.name;
}
»
Reference Error
A ReferenceError is thrown if you use (reference) a variable that has not been declared:

Example
var x;
try {
    x = y + 1;   // y cannot be referenced (used)
}
catch(err) {
    document.getElementById(“demo”).innerHTML = err.name;
}
»
Syntax Error
A SyntaxError is thrown if you try to evaluate code with a syntax error.

Example
try {
    eval(“alert(‘Hello)”);   // Missing ‘ will produce an error
}
catch(err) {
    document.getElementById(“demo”).innerHTML = err.name;
}
»
Type Error
A TypeError is thrown if you use a value that is outside the range of expected types:

Example
var num = 1;
try {
    num.toUpperCase();   // You cannot convert a number to upper case
}
catch(err) {
    document.getElementById(“demo”).innerHTML = err.name;
}
»
URI Error
A URIError is thrown if you use illegal characters in a URI function:

Example
try {
    decodeURI(“%%%”);   // You cannot URI decode these percent signs
}
catch(err) {
    document.getElementById(“demo”).innerHTML = err.name;
}
»
Non-Standard Error Object Properties
Mozilla and Microsoft defines some non-standard error object properties:

fileName (Mozilla)
lineNumber (Mozilla)
columnNumber (Mozilla)
stack (Mozilla)
description (Microsoft)
number (Microsoft)

Do not use these properties in public web sites. They will not work in all browsers.

❮ Previous Next ❯

JavaScript Debugging

Toggle navigation
TUTORIAL HOME
JavaScript Debugging
❮ Previous Next ❯

Errors can (will) happen, every time you write some new computer code.

Code Debugging
Programming code might contain syntax errors, or logical errors.

Many of these errors are difficult to diagnose.

Often, when programming code contains errors, nothing will happen. There are no error messages, and you will get no indications where to search for errors.

Searching for (and fixing) errors in programming code is called code debugging.

JavaScript Debuggers
Debugging is not easy. But fortunately, all modern browsers have a built-in JavaScript debugger.

Built-in debuggers can be turned on and off, forcing errors to be reported to the user.

With a debugger, you can also set breakpoints (places where code execution can be stopped), and examine variables while the code is executing.

Normally, otherwise follow the steps at the bottom of this page, you activate debugging in your browser with the F12 key, and select “Console” in the debugger menu.

The console.log() Method
If your browser supports debugging, you can use console.log() to display JavaScript values in the debugger window:

Example

My First Web Page

a = 5;
b = 6;
c = a + b;
console.log(c);

»
Setting Breakpoints
In the debugger window, you can set breakpoints in the JavaScript code.

At each breakpoint, JavaScript will stop executing, and let you examine JavaScript values.

After examining values, you can resume the execution of code (typically with a play button).

The debugger Keyword
The debugger keyword stops the execution of JavaScript, and calls (if available) the debugging function.

This has the same function as setting a breakpoint in the debugger.

If no debugging is available, the debugger statement has no effect.

With the debugger turned on, this code will stop executing before it executes the third line.

Example
var x = 15 * 5;
debugger;
document.getElementbyId(“demo”).innerHTML = x;
»
Major Browsers’ Debugging Tools
Normally, you activate debugging in your browser with F12, and select “Console” in the debugger menu.

Otherwise follow these steps:

Chrome
Open the browser.
From the menu, select tools.
From tools, choose developer tools.
Finally, select Console.
Firefox Firebug
Open the browser.
Go to the web page:
http://www.getfirebug.com
Follow the instructions how to:
install Firebug
Internet Explorer
Open the browser.
From the menu, select tools.
From tools, choose developer tools.
Finally, select Console.
Opera
Open the browser.
Go to the webpage:
http://dev.opera.com
Follow the instructions how to:
add a Developer Console button to your toolbar.
Safari Firebug
Open the browser.
Go to the webpage:
http://safari-extensions.apple.com
Follow the instructions how to:
install Firebug Lite.
Safari Develop Menu
Go to Safari, Preferences, Advanced in the main menu.
Check “Enable Show Develop menu in menu bar”.
When the new option “Develop” appears in the menu:
Choose “Show Error Console”.
Did You Know?
Debugging is the process of testing, finding, and reducing bugs (errors) in computer programs.
The first known computer bug was a real bug (an insect) stuck in the electronics.

❮ Previous Next ❯

JavaScript Hoisting

JavaScript Hoisting
❮ Previous Next ❯
Hoisting is JavaScript’s default behavior of moving declarations to the top.

JavaScript Declarations are Hoisted
In JavaScript, a variable can be declared after it has been used.

In other words; a variable can be used before it has been declared.

Example 1 gives the same result as Example 2:

Example 1
x = 5; // Assign 5 to x

elem = document.getElementById(“demo”); // Find an element
elem.innerHTML = x;                     // Display x in the element

var x; // Declare x
»

Example 2
var x; // Declare x
x = 5; // Assign 5 to x

elem = document.getElementById(“demo”); // Find an element
elem.innerHTML = x;                     // Display x in the element
»
To understand this, you have to understand the term “hoisting”.

Hoisting is JavaScript’s default behavior of moving all declarations to the top of the current scope (to the top of the current script or the current function).

JavaScript Initializations are Not Hoisted
JavaScript only hoists declarations, not initializations.

Example 1 does not give the same result as Example 2:

Example 1
var x = 5; // Initialize x
var y = 7; // Initialize y

elem = document.getElementById(“demo”); // Find an element
elem.innerHTML = x + ” ” + y;           // Display x and y
»

Example 2
var x = 5; // Initialize x

elem = document.getElementById(“demo”); // Find an element
elem.innerHTML = x + ” ” + y;           // Display x and y

var y = 7; // Initialize y
»
Does it make sense that y is undefined in the last example?

This is because only the declaration (var y), not the initialization (=7) is hoisted to the top.

Because of hoisting, y has been declared before it is used, but because initializations are not hoisted, the value of y is undefined.

Example 2 is the same as writing:

Example
var x = 5; // Initialize x
var y;     // Declare y

elem = document.getElementById(“demo”); // Find an element
elem.innerHTML = x + ” ” + y;           // Display x and y

y = 7;    // Assign 7 to y
»
Declare Your Variables At the Top !
Hoisting is (to many developers) an unknown or overlooked behavior of JavaScript.

If a developer doesn’t understand hoisting, programs may contain bugs (errors).

To avoid bugs, always declare all variables at the beginning of every scope.

Since this is how JavaScript interprets the code, it is always a good rule.

JavaScript in strict mode does not allow variables to be used if they are not declared.
Study “use strict” in the next chapter.

❮ Previous Next ❯

JavaScript Use Strict

Toggle navigation
TUTORIAL HOME
JavaScript Use Strict
❮ Previous Next ❯
“use strict”; Defines that JavaScript code should be executed in “strict mode”.

The “use strict” Directive
The “use strict” directive is new in JavaScript 1.8.5 (ECMAScript version 5).

It is not a statement, but a literal expression, ignored by earlier versions of JavaScript.

The purpose of “use strict” is to indicate that the code should be executed in “strict mode”.

With strict mode, you can not, for example, use undeclared variables.

Strict mode is supported in:
IE from version 10. Firefox from version 4.
Chrome from version 13. Safari from version 5.1.
Opera from version 12.

Declaring Strict Mode
Strict mode is declared by adding “use strict”; to the beginning of a script or a function.

Declared at the beginning of a script, it has global scope (all code in the script will execute in strict mode):

Example
“use strict”;
x = 3.14;       // This will cause an error because x is not declared
»
Example
“use strict”;
myFunction();

function myFunction() {
    y = 3.14;   // This will also cause an error because y is not declared
}
»
Declared inside a function, it has local scope (only the code inside the function is in strict mode):

x = 3.14;       // This will not cause an error.
myFunction();

function myFunction() {
   “use strict”;
    y = 3.14;   // This will cause an error
}
»
The “use strict”; Syntax
The syntax, for declaring strict mode, was designed to be compatible with older versions of JavaScript.

Compiling a numeric literal (4 + 5;) or a string literal (“John Doe”;) in a JavaScript program has no side effects. It simply compiles to a non existing variable and dies.

So “use strict”; only matters to new compilers that “understand” the meaning of it.

Why Strict Mode?
Strict mode makes it easier to write “secure” JavaScript.

Strict mode changes previously accepted “bad syntax” into real errors.

As an example, in normal JavaScript, mistyping a variable name creates a new global variable. In strict mode, this will throw an error, making it impossible to accidentally create a global variable.

In normal JavaScript, a developer will not receive any error feedback assigning values to non-writable properties.

In strict mode, any assignment to a non-writable property, a getter-only property, a non-existing property, a non-existing variable, or a non-existing object, will throw an error.

Not Allowed in Strict Mode
Using a variable, without declaring it, is not allowed:

“use strict”;
x = 3.14;                // This will cause an error
»

Objects are variables too.

Using an object, without declaring it, is not allowed:

“use strict”;
x = {p1:10, p2:20};      // This will cause an error
»

Deleting a variable (or object) is not allowed.

“use strict”;
var x = 3.14;
delete x;                // This will cause an error
»

Deleting a function is not allowed.

“use strict”;
function x(p1, p2) {};
delete x;                // This will cause an error
»

Duplicating a parameter name is not allowed:

“use strict”;
function x(p1, p1) {};   // This will cause an error
»

Octal numeric literals are not allowed:

“use strict”;
var x = 010;             // This will cause an error
»

Escape characters are not allowed:

“use strict”;
var x = \010;            // This will cause an error
»

Writing to a read-only property is not allowed:

“use strict”;
var obj = {};
Object.defineProperty(obj, “x”, {value:0, writable:false});

obj.x = 3.14;            // This will cause an error
»

Writing to a get-only property is not allowed:

“use strict”;
var obj = {get x() {return 0} };

obj.x = 3.14;            // This will cause an error
»

Deleting an undeletable property is not allowed:

“use strict”;
delete Object.prototype; // This will cause an error
»

The string “eval” cannot be used as a variable:

“use strict”;
var eval = 3.14;         // This will cause an error
»

The string “arguments” cannot be used as a variable:

“use strict”;
var arguments = 3.14;    // This will cause an error
»

The with statement is not allowed:

“use strict”;
with (Math){x = cos(2)}; // This will cause an error
»

For security reasons, eval() is not allowed to create variables in the scope from which it was called:

“use strict”;
eval (“var x = 2”);
alert (x);               // This will cause an error
»

In function calls like f(), the this value was the global object. In strict mode, it is now undefined.

Future Proof!
Future reserved keywords are not allowed in strict mode. These are:

implements
interface
let
package
private
protected
public
static
yield
“use strict”;
var public = 1500;      // This will cause an error
»

Watch Out!
The “use strict” directive is only recognized at the beginning of a script or a function.

❮ Previous Next ❯

JavaScript Style Guide and Coding Conventions

Toggle navigation
TUTORIAL HOME
JavaScript Style Guide and Coding Conventions
❮ Previous Next ❯
Always use the same coding conventions for all your JavaScript projects.

JavaScript Coding Conventions
Coding conventions are style guidelines for programming. They typically cover:

Naming and declaration rules for variables and functions.
Rules for the use of white space, indentation, and comments.
Programming practices and principles
Coding conventions secure quality:

Improves code readability
Make code maintenance easier
Coding conventions can be documented rules for teams to follow, or just be your individual coding practice.

This page describes the general JavaScript code conventions used by Omegas.
You should also read the next chapter “Best Practices”, and learn how to avoid coding pitfalls.

Variable Names
At Omegas we use camelCase for identifier names (variables and functions).

All names start with a letter.

At the bottom of this page, you will find a wider discussion about naming rules.

firstName = “John”;
lastName = “Doe”;

price = 19.90;
tax = 0.20;

fullPrice = price + (price * tax);
Spaces Around Operators
Always put spaces around operators ( = + – * / ), and after commas:

Examples:
var x = y + z;
var values = [“Volvo”, “Saab”, “Fiat”];
Code Indentation
Always use 4 spaces for indentation of code blocks:

Functions:
function toCelsius(fahrenheit) {
    return (5 / 9) * (fahrenheit – 32);
}
Do not use tabs (tabulators) for indentation. Different editors interpret tabs differently.

Statement Rules
General rules for simple statements:

Always end a simple statement with a semicolon.
Examples:
var values = [“Volvo”, “Saab”, “Fiat”];

var person = {
    firstName: “John”,
    lastName: “Doe”,
    age: 50,
    eyeColor: “blue”
};
General rules for complex (compound) statements:

Put the opening bracket at the end of the first line.
Use one space before the opening bracket.
Put the closing bracket on a new line, without leading spaces.
Do not end a complex statement with a semicolon.
Functions:
function toCelsius(fahrenheit) {
    return (5 / 9) * (fahrenheit – 32);
}

Loops:
for (i = 0; i < 5; i++) {
    x += i;
}

Conditionals:
if (time < 20) {
    greeting = “Good day”;
} else {
    greeting = “Good evening”;
}
Object Rules
General rules for object definitions:

Place the opening bracket on the same line as the object name.
Use colon plus one space between each property and its value.
Use quotes around string values, not around numeric values.
Do not add a comma after the last property-value pair.
Place the closing bracket on a new line, without leading spaces.
Always end an object definition with a semicolon.
Example
var person = {
    firstName: “John”,
    lastName: “Doe”,
    age: 50,
    eyeColor: “blue”
};
Short objects can be written compressed, on one line, using spaces only between properties, like this:

var person = {firstName:”John”, lastName:”Doe”, age:50, eyeColor:”blue”};
Line Length < 80
For readability, avoid lines longer than 80 characters.

If a JavaScript statement does not fit on one line, the best place to break it, is after an operator or a comma.

Example
document.getElementById(“demo”).innerHTML =
    “Hello Dolly.”;
»
Naming Conventions
Always use the same naming convention for all your code. For example:

Variable and function names written as camelCase
Global variables written in UPPERCASE (We don’t, but it’s quite common)
Constants (like PI) written in UPPERCASE
Should you use hyp-hens, camelCase, or under_scores in variable names?

This is a question programmers often discuss. The answer depends on who you ask:

Hyphens in HTML and CSS:

HTML5 attributes can start with data- (data-quantity, data-price).

CSS uses hyphens in property-names (font-size).

Hyphens can be mistaken as subtraction attempts. Hyphens are not allowed in JavaScript names.

Underscores:

Many programmers prefer to use underscores (date_of_birth), especially in SQL databases.

Underscores are often used in PHP documentation.

PascalCase:

PascalCase is often preferred by C programmers.

camelCase:

camelCase is used by JavaScript itself, by jQuery, and other JavaScript libraries.

Do not start names with a $ sign. It will put you in conflict with many JavaScript library names.

Loading JavaScript in HTML
Use simple syntax for loading external scripts (the type attribute is not necessary):

http://myscript.js
Accessing HTML Elements
A consequence of using “untidy” HTML styles, might result in JavaScript errors.

These two JavaScript statements will produce different results:

var obj = getElementById(“Demo”)

var obj = getElementById(“demo”)
If possible, use the same naming convention (as JavaScript) in HTML.

Visit the HTML Style Guide.

File Extensions
HTML files should have a .html extension (not .htm).

CSS files should have a .css extension.

JavaScript files should have a .js  extension.

Use Lower Case File Names
Most web servers (Apache, Unix) are case sensitive about file names:

london.jpg cannot be accessed as London.jpg.

Other web servers (Microsoft, IIS) are not case sensitive:

london.jpg can be accessed as London.jpg or london.jpg.

If you use a mix of upper and lower case, you have to be extremely consistent.

If you move from a case insensitive, to a case sensitive server, even small errors can break your web site.

To avoid these problems, always use lower case file names (if possible).

Performance
Coding conventions are not used by computers. Most rules have little impact on the execution of programs.

Indentation and extra spaces are not significant in small scripts.

For code in development, readability should be preferred. Larger production scripts should be minified.

❮ Previous Next ❯

JavaScript Statements

Toggle navigation
TUTORIAL HOME
JavaScript Statements
❮ Previous Next ❯
In HTML, JavaScript statements are “instructions” to be “executed” by the web browser.

JavaScript Statements
This statement tells the browser to write “Hello Dolly.” inside an HTML element with id=”demo”:

Example
document.getElementById(“demo”).innerHTML = “Hello Dolly.”;
»
JavaScript Programs
Most JavaScript programs contain many JavaScript statements.

The statements are executed, one by one, in the same order as they are written.

In this example x, y, and z are given values, and finally z is displayed:

Example
var x, y, z;
x = 5;
y = 6;
z = x + y;
document.getElementById(“demo”).innerHTML = z;
»
JavaScript programs (and JavaScript statements) are often called JavaScript code.

Semicolons ;
Semicolons separate JavaScript statements.

Add a semicolon at the end of each executable statement:

var a, b, c;
a = 5;
b = 6;
c = a + b;
»
When separated by semicolons, multiple statements on one line are allowed:

a = 5; b = 6; c = a + b;
»
On the web, you might see examples without semicolons.
Ending statements with semicolon is not required, but highly recommended.

JavaScript White Space
JavaScript ignores multiple spaces. You can add white space to your script to make it more readable.

The following lines are equivalent:

var person = “Hege”;
var person=”Hege”;
A good practice is to put spaces around operators ( = + – * / ):

var x = y + z;
JavaScript Line Length and Line Breaks
For best readability, programmers often like to avoid code lines longer than 80 characters.

If a JavaScript statement does not fit on one line, the best place to break it, is after an operator:

Example
document.getElementById(“demo”).innerHTML =
“Hello Dolly.”;
»
JavaScript Code Blocks
JavaScript statements can be grouped together in code blocks, inside curly brackets {…}.

The purpose of code blocks is to define statements to be executed together.

One place you will find statements grouped together in blocks, is in JavaScript functions:

Example
function myFunction() {
    document.getElementById(“demo1”).innerHTML = “Hello Dolly.”;
    document.getElementById(“demo2”).innerHTML = “How are you?”;
}
»
In this tutorial we use 4 spaces of indentation for code blocks.
You will learn more about functions later in this tutorial.

JavaScript Keywords
JavaScript statements often start with a keyword to identify the JavaScript action to be performed.

Here is a list of some of the keywords you will learn about in this tutorial:

Keyword Description
break Terminates a switch or a loop
continue Jumps out of a loop and starts at the top
debugger Stops the execution of JavaScript, and calls (if available) the debugging function
do … while Executes a block of statements, and repeats the block, while a condition is true
for Marks a block of statements to be executed, as long as a condition is true
function Declares a function
if … else Marks a block of statements to be executed, depending on a condition
return Exits a function
switch Marks a block of statements to be executed, depending on different cases
try … catch Implements error handling to a block of statements
var Declares a variable
JavaScript keywords are reserved words. Reserved words cannot be used as names for variables.

❮ Previous Next ❯

JavaScript Assignment

Toggle navigation
TUTORIAL HOME
JavaScript Assignment
❮ Previous Next ❯
JavaScript Assignment Operators
Assignment operators assign values to JavaScript variables.

Operator Example Same As
= x = y x = y
+= x += y x = x + y
-= x -= y x = x – y
*= x *= y x = x * y
/= x /= y x = x / y
%= x %= y x = x % y
<<= x <<= y x = x << y
>>= x >>= y x = x >> y
>>>= x >>>= y x = x >>> y
&= x &= y x = x & y
^= x ^= y x = x ^ y
|= x |= y x = x | y
**= x **= y x = x ** y
The **= operator is an experimental part of the ECMAScript 2016 proposal (ES7). It is not stable across browsers. Do not use it.

Assignment Examples
The = assignment operator assigns a value to a variable.

Assignment
var x = 10;
»
The += assignment operator adds a value to a variable.

Assignment
var x = 10;
x += 5;
»
The -= assignment operator subtracts a value from a variable.

Assignment
var x = 10;
x -= 5;
»
The *= assignment operator multiplies a variable.

Assignment
var x = 10;
x *= 5;
»
The /= assignment divides a variable.

Assignment
var x = 10;
x /= 5;
»
The %= assignment operator assigns a remainder to a variable.

Assignment
var x = 10;
x %= 5;
»
Test Yourself with Exercises!
Exercise 1 »  Exercise 2 »  Exercise 3 »  Exercise 4 »  Exercise 5 »

❮ Previous Next ❯

JavaScript String Methods

TUTORIAL HOME
JavaScript String Methods
❮ Previous Next ❯
String methods help you to work with strings.

String Methods and Properties
Primitive values, like “John Doe”, cannot have properties or methods (because they are not objects).

But with JavaScript, methods and properties are also available to primitive values, because JavaScript treats primitive values as objects when executing methods and properties.

String Length
The length property returns the length of a string:

Example
var txt = “ABCDEFGHIJKLMNOPQRSTUVWXYZ”;
var sln = txt.length;
»
Finding a String in a String
The indexOf() method returns the index of (the position of) the first occurrence of a specified text in a string:

Example
var str = “Please locate where ‘locate’ occurs!”;
var pos = str.indexOf(“locate”);
»
The lastIndexOf() method returns the index of the last occurrence of a specified text in a string:

Example
var str = “Please locate where ‘locate’ occurs!”;
var pos = str.lastIndexOf(“locate”);
»
Both the indexOf(), and the lastIndexOf() methods return -1 if the text is not found.

JavaScript counts positions from zero.
0 is the first position in a string, 1 is the second, 2 is the third …

Both methods accept a second parameter as the starting position for the search.

Searching for a String in a String
The search() method searches a string for a specified value and returns the position of the match:

Example
var str = “Please locate where ‘locate’ occurs!”;
var pos = str.search(“locate”);
»
Did You Notice?
The two methods, indexOf() and search(), are equal.

They accept the same arguments (parameters), and they return the same value.

The two methods are equal, but the search() method can take much more powerful search values.

You will learn more about powerful search values in the chapter about regular expressions.

Extracting String Parts
There are 3 methods for extracting a part of a string:

slice(start, end)
substring(start, end)
substr(start, length)
The slice() Method
slice() extracts a part of a string and returns the extracted part in a new string.

The method takes 2 parameters: the starting index (position), and the ending index (position).

This example slices out a portion of a string from position 7 to position 13:

Example
var str = “Apple, Banana, Kiwi”;
var res = str.slice(7, 13);
The result of res will be:

Banana
»
If a parameter is negative, the position is counted from the end of the string.

This example slices out a portion of a string from position -12 to position -6:

Example
var str = “Apple, Banana, Kiwi”;
var res = str.slice(-12, -6);
The result of res will be:

Banana
»
If you omit the second parameter, the method will slice out the rest of the string:

Example
var res = str.slice(7);
»
or, counting from the end:

Example
var res = str.slice(-12);
»
Negative positions do not work in Internet Explorer 8 and earlier.

The substring() Method
substring() is similar to slice().

The difference is that substring() cannot accept negative indexes.

Example
var str = “Apple, Banana, Kiwi”;
var res = str.substring(7, 13);
The result of res will be:

Banana
»
If you omit the second parameter, substring() will slice out the rest of the string.

The substr() Method
substr() is similar to slice().

The difference is that the second parameter specifies the length of the extracted part.

Example
var str = “Apple, Banana, Kiwi”;
var res = str.substr(7, 6);
The result of res will be:

Banana
»
If the first parameter is negative, the position counts from the end of the string.

The second parameter can not be negative, because it defines the length.

If you omit the second parameter, substr() will slice out the rest of the string.

Replacing String Content
The replace() method replaces a specified value with another value in a string:

Example
str = “Please visit Microsoft!”;
var n = str.replace(“Microsoft”, “Omegas”);
»
The replace() method can also take a regular expression as the search value.

By default, the replace() function replaces only the first match. To replace all matches, use a regular expression with a g flag (for global match):
Example
str = “Please visit Microsoft!”;
var n = str.replace(/Microsoft/g, “Omegas”);
»
The replace() method does not change the string it is called on. It returns a new string.

Converting to Upper and Lower Case
A string is converted to upper case with toUpperCase():

Example
var text1 = “Hello World!”;       // String
var text2 = text1.toUpperCase();  // text2 is text1 converted to upper
»
A string is converted to lower case with  toLowerCase():

Example
var text1 = “Hello World!”;       // String
var text2 = text1.toLowerCase();  // text2 is text1 converted to lower
»
The concat() Method
concat() joins two or more strings:

Example
var text1 = “Hello”;
var text2 = “World”;
text3 = text1.concat(” “, text2);
»
The concat() method can be used instead of the plus operator. These two lines do the same:

Example
var text = “Hello” + ” ” + “World!”;
var text = “Hello”.concat(” “, “World!”);
All string methods return a new string. They don’t modify the original string.
Formally said: Strings are immutable: Strings cannot be changed, only replaced.

Extracting String Characters
There are 2 safe methods for extracting string characters:

charAt(position)
charCodeAt(position)
The charAt() Method
The charAt() method returns the character at a specified index (position) in a string:

Example
var str = “HELLO WORLD”;
str.charAt(0);            // returns H
»
The charCodeAt() Method
The charCodeAt() method returns the unicode of the character at a specified index in a string:

Example
var str = “HELLO WORLD”;

str.charCodeAt(0);         // returns 72
»
Accessing a String as an Array is Unsafe
You might have seen code like this, accessing a string as an array:

var str = “HELLO WORLD”;

str[0];                   // returns H
This is unsafe and unpredictable:

It does not work in all browsers (not in IE5, IE6, IE7)
It makes strings look like arrays (but they are not)
str[0] = “H” does not give an error (but does not work)
If you want to read a string as an array, convert it to an array first.

Converting a String to an Array
A string can be converted to an array with the split() method:

Example
var txt = “a,b,c,d,e”;   // String
txt.split(“,”);          // Split on commas
txt.split(” “);          // Split on spaces
txt.split(“|”);          // Split on pipe
»
If the separator is omitted, the returned array will contain the whole string in index [0].

If the separator is “”, the returned array will be an array of single characters:

Example
var txt = “Hello”;       // String
txt.split(“”);           // Split in characters
»
Complete String Reference
For a complete reference, go to our Complete JavaScript String Reference.

The reference contains descriptions and examples of all string properties and methods.

Test Yourself with Exercises!
Exercise 1 »  Exercise 2 »  Exercise 3 »  Exercise 4 »  Exercise 5 »  Exercise 6 »

❮ Previous Next ❯

JavaScript Strings

Toggle navigation
TUTORIAL HOME
JavaScript Strings
❮ Previous Next ❯
JavaScript strings are used for storing and manipulating text.

JavaScript Strings
A JavaScript string simply stores a series of characters like “John Doe”.

A string can be any text inside quotes. You can use single or double quotes:

Example
var carname = “Volvo XC60”;
var carname = ‘Volvo XC60’;
»
You can use quotes inside a string, as long as they don’t match the quotes surrounding the string:

Example
var answer = “It’s alright”;
var answer = “He is called ‘Johnny'”;
var answer = ‘He is called “Johnny”‘;
»
String Length
The length of a string is found in the built in property length:

Example
var txt = “ABCDEFGHIJKLMNOPQRSTUVWXYZ”;
var sln = txt.length;
»
Special Characters
Because strings must be written within quotes, JavaScript will misunderstand this string:

var y = “We are the so-called “Vikings” from the north.”
The string will be chopped to “We are the so-called “.

The solution to avoid this problem, is to use the \ escape character.

The backslash escape character turns special characters into string characters:

Example
var x = ‘It\’s alright’;
var y = “We are the so-called \”Vikings\” from the north.”
»
The escape character (\) can also be used to insert other special characters in a string.

These are commonly used special characters that can be inserted in a text with the backslash sign:

Code Outputs
\’ single quote
\” double quote
\\ backslash
Five other escape characters are valid in JavaScript:

Code Outputs
\b Backspace
\r Carriage Return
\f Form Feed
\t Horizontal Tabulator
\v Vertical Tabulator
The escape characters above were originally designed to control typewriters, teletypes, and fax machines. They do not make any sense in HTML.

Breaking Long Code Lines
For best readability, programmers often like to avoid code lines longer than 80 characters.

If a JavaScript statement does not fit on one line, the best place to break it is after an operator:

Example
document.getElementById(“demo”).innerHTML =
“Hello Dolly.”;
»
You can also break up a code line within a text string with a single backslash:

Example
document.getElementById(“demo”).innerHTML = “Hello \
Dolly!”;
»
The \ method is not the preferred method. It might not have universal support.
Some browsers do not allow spaces behind the \ character.

A safer way to break up a string, is to use string addition:

Example
document.getElementById(“demo”).innerHTML = “Hello” +
“Dolly!”;
»
You cannot break up a code line with a backslash:

Example
document.getElementById(“demo”).innerHTML = \
“Hello Dolly!”;
»
Strings Can be Objects
Normally, JavaScript strings are primitive values, created from literals: var firstName = “John”

But strings can also be defined as objects with the keyword new: var firstName = new String(“John”)

Example
var x = “John”;
var y = new String(“John”);

// typeof x will return string
// typeof y will return object
»
Don’t create strings as objects. It slows down execution speed.
The new keyword complicates the code. This can produce some unexpected results:

When using the == operator, equal strings are equal:

Example
var x = “John”;            
var y = new String(“John”);

// (x == y) is true because x and y have equal values
»
When using the === operator, equal strings are not equal, because the === operator expects equality in both type and value.

Example
var x = “John”;            
var y = new String(“John”);

// (x === y) is false because x and y have different types (string and object)
»
Or even worse. Objects cannot be compared:

Example
var x = new String(“John”);            
var y = new String(“John”);

// (x == y) is false because x and y are different objects
»
Example
var x = new String(“John”);            
var y = new String(“John”);

// (x === y) is false because x and y are different objects
»
Note the difference between (x==y) and (x===y).
Comparing two JavaScript objects will always return false.

Test Yourself with Exercises!
Exercise 1 »   Exercise 2 »   Exercise 3 »   Exercise 4 »

❮ Previous Next ❯