Skip to content

JavaScript Basics

ApplefaceLisa edited this page Jan 6, 2017 · 12 revisions

String Methods

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.

Complete String Reference

String Length

The length property returns the length of a string:

var txt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
var sln = txt.length;   // 26

Finding a String in a String

  • indexOf()

The indexOf() method returns the index of (the position of) the first occurrence of a specified text in a string:

var str = "Please locate where 'locate' occurs!";
var pos = str.indexOf("locate");   // 7
  • lastIndexOf()

The lastIndexOf() method returns the index of the last occurrence of a specified text in a string:

var str = "Please locate where 'locate' occurs!";
var pos = str.lastIndexOf("locate");   // 21

Both the indexOf(), and the lastIndexOf() methods return -1 if the text is not found.

Searching for a String in a String

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

var str = "Please locate where 'locate' occurs!";
var pos = str.search("locate");  // 7

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, inclusive), and the ending index (position, exclusive).

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

var str = "Apple, Banana, Kiwi";
var res = str.slice(7, 13);  // "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:

var str = "Apple, Banana, Kiwi";
var res = str.slice(-12, -6);   // "Banana"

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

var res = str.slice(7); // "Banana, Kiwi" var res = str.slice(-4); // "Kiwi"

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.

var str = "Apple, Banana, Kiwi";
var res = str.substring(7, 13);   // "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.

var str = "Apple, Banana, Kiwi";
var res = str.substr(7, 6);   // "Banana"

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

var str = "Apple, Banana, Kiwi";
var res = str.substr(-4, 3);   // "Kiw"

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.

var str = "Apple, Banana, Kiwi";
var res = str.substr(12);   // "a, Kiwi"

Replacing String Content

The replace() method replaces a specified value with another value in a string. It does not change the string it is called on. It returns a new string.

str = "Please visit Microsoft!";
var n = str.replace("Microsoft", "W3Schools");   // "Please visit W3Schools!"

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):

str = "Please visit Microsoft and Microsoft!";
var n = str.replace(/Microsoft/, "W3Schools");  // "Please visit W3Schools and Microsoft!"

str = "Please visit Microsoft and Microsoft!";
var n = str.replace(/Microsoft/g, "W3Schools"); // "Please visit W3Schools and W3Schools!"

Converting to Upper and Lower Case

A string is converted to upper case with toUpperCase():

var text1 = "Hello World!";       // String
var text2 = text1.toUpperCase();  // "HELLO WORLD!"

A string is converted to lower case with toLowerCase():

var text1 = "Hello World!"; // String var text2 = text1.toLowerCase(); // "hello world!"

Joint two or more Strings

concat() joins two or more strings:

var text1 = "Hello";
var text2 = "World";
text3 = text1.concat(" ", text2);   // "Hello World!"

The concat() method can be used instead of the plus operator. These two lines do the same:

var text = "Hello" + " " + "World!";
var text = "Hello".concat(" ", "World!");

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:

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:

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:

var txt = "a,b,c,d,e";    // String
var arr = txt.split(","); // Split on commas, arr = ['a','b','c','d','e'].
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]:

var txt = "a,b,c,d,e";
var arr = txt.split();
console.log(arr[0]);  // "a,b,c,d,e"

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

var txt = "a,b,c,d,e";
var arr = txt.split("");  // arr = ['a',',','b',',','c',',','d',',','e']

var txt = "Hello";       // String
txt.split("");           // Split in characters, ['H','e','l','l','o']

JavaScript Numbers

JavaScript Numbers are Always 64-bit Floating Point.

JavaScript numbers are always stored as double precision floating point numbers, following the international IEEE 754 standard.

This format stores numbers in 64 bits, where the number (the fraction) is stored in bits 0 to 51, the exponent in bits 52 to 62, and the sign in bit 63.

Precision

Integers (numbers without a period or exponent notation) are considered accurate up to 15 digits.

var x = 999999999999999;   // x will be 999999999999999
var y = 9999999999999999;  // y will be 10000000000000000

The maximum number of decimals is 17.

Floating point arithmetic is not always 100% accurate:

var x = 0.2 + 0.1;         // x will be 0.30000000000000004

To solve the problem above, it helps to multiply and divide:

var x = (0.2 * 10 + 0.1 * 10) / 10;       // x will be 0.3

Infinity

Infinity (or -Infinity) is the value JavaScript will return if you calculate a number outside the largest possible number.

Division by 0 (zero) also generates Infinity:

var x =  2 / 0;          // x will be Infinity
var y = -2 / 0;          // y will be -Infinity

Infinity is a number: typeof Infinity returns number.

typeof Infinity;        // returns "number"

NaN - Not a Number

NaN is a JavaScript reserved word indicating that a number is not a legal number.

Trying to do arithmetic with a non-numeric string will result in NaN (Not a Number):

var x = 100 / "Apple";  // x will be NaN (Not a Number)

However, if the string contains a numeric value , the result will be a number:

var x = 100 / "10";     // x will be 10

You can use the global JavaScript function isNaN() to find out if a value is a number.

var x = 100 / "Apple";
isNaN(x);               // returns true because x is Not a Number

If you use NaN in a mathematical operation, the result will also be NaN.

Number Methods

  • toString()
  • toExponential()
  • toFixed()
  • toPrecision()
  • valueOf()

toString()

returns a number as a string.

var x = 123;
x.toString();            // returns "123" from variable x
(123).toString();        // returns "123" from literal 123
(100 + 23).toString();   // returns "123" from expression 100 + 23

you can use the toString() method to output numbers as base 16 (hex), base 8 (octal), or base 2 (binary):

var myNumber = 128;
myNumber.toString(16);     // returns "80"
myNumber.toString(8);      // returns "200"
myNumber.toString(2);      // returns "10000000"

toExponential()

returns a string, with a number rounded and written using exponential notation.

A parameter defines the number of characters behind the decimal point:

var x = 9.656;
x.toExponential()       // returns "9.656e+0"
x.toExponential(2);     // returns "9.66e+0"
x.toExponential(4);     // returns "9.6560e+0"
x.toExponential(6);     // returns "9.656000e+0"

var x = 1999.656;
x.toExponential()       // returns "1.999656e+3"
x.toExponential(2);     // returns "2.00e+3"
x.toExponential(4);     // returns "1.9997e+3"
x.toExponential(6);     // returns "1.999656e+3"

The parameter is optional. If you don't specify it, JavaScript will not round the number.

toFixed()

returns a string, with the number written with a specified number of decimals:

var x = 9.656;
x.toFixed(0);           // returns "10"
x.toFixed(2);           // returns "9.66"
x.toFixed(4);           // returns "9.6560"
x.toFixed(6);           // returns "9.656000"

toFixed(2) is perfect for working with money.

toPrecision()

returns a string, with a number written with a specified length:

var x = 9.656;
x.toPrecision();        // returns "9.656"
x.toPrecision(2);       // returns "9.7"
x.toPrecision(4);       // returns "9.656"
x.toPrecision(6);       // returns "9.65600"

valueOf()

returns a number as a number.

var x = 123;
x.valueOf();            // returns 123 from variable x
(123).valueOf();        // returns 123 from literal 123
(100 + 23).valueOf();   // returns 123 from expression 100 + 23

In JavaScript, a number can be a primitive value (typeof = number) or an object (typeof = object).

The valueOf() method is used internally in JavaScript to convert Number objects to primitive values.

There is no reason to use it in your code.

All JavaScript data types have a valueOf() and a toString() method.

Converting Variables to Numbers

There are 3 JavaScript methods that can be used to convert variables to numbers:

  • The Number() method : Returns a number, converted from its argument.
  • The parseInt() method : Parses its argument and returns an integer.
  • The parseFloat() method : Parses its argument and returns a floating point number.

These methods are not number methods, but global JavaScript methods. JavaScript global methods can be used on all JavaScript data types.

// Number() can be used to convert JavaScript variables to numbers:
x = true;
Number(x);        // returns 1
x = false;     
Number(x);        // returns 0
x = new Date();
Number(x);        // returns 1404568027739
x = "10"
Number(x);        // returns 10
x = "10 20"
Number(x);        // returns NaN

// parseInt() parses a string and returns a whole number. Spaces are allowed. Only the first number is returned:
parseInt("10");         // returns 10
parseInt("10.33");      // returns 10
parseInt("10 20 30");   // returns 10
parseInt("10 years");   // returns 10
parseInt("years 10");   // returns NaN 

// parseFloat() parses a string and returns a number. Spaces are allowed. Only the first number is returned:
parseFloat("10");        // returns 10
parseFloat("10.33");     // returns 10.33
parseFloat("10 20 30");  // returns 10
parseFloat("10 years");  // returns 10
parseFloat("years 10");  // returns NaN

Number Properties

  • Property Description
  • MAX_VALUE Returns the largest number possible in JavaScript
  • MIN_VALUE Returns the smallest number possible in JavaScript
  • NEGATIVE_INFINITY Represents negative infinity (returned on overflow)
  • NaN Represents a "Not-a-Number" value
  • POSITIVE_INFINITY Represents infinity (returned on overflow)

Number properties belongs to the JavaScript's number object wrapper called Number.

These properties can only be accessed as Number.MAX_VALUE.

var x = Number.MAX_VALUE;         // 1.7976931348623157e+308
var x = Number.MIN_VALUE;         // 5e-324
var x = Number.NEGATIVE_INFINITY; // -Infinity
var x = Number.NaN;               // NaN
var x = Number.POSITIVE_INFINITY; // Infinity

Using myNumber.MAX_VALUE, where myNumber is a variable, expression, or value, will return undefined:

var x = 6;
var y = x.MAX_VALUE;    // y becomes undefined

Credit

Thanks for W3School.

Clone this wiki locally