Common JavaScript Manual/Data types - Strings

Strings

edit

Let's make a variable with a string as value; we will use string literal. Strings can be enclosed in double and single quotes (though in most languages strings are enclosed in double quotes and chars in single quotes).

str = "Hello, ";

Concatenation

edit

We can concatenate strings using '+' operator. Let's add to string in variable 'a' string "world".

str = str + "world!"; // Hello, world!

Length of string

edit

Any string has a 'length' property that contains the number of chars in the string.

str.length; // 13

Split

edit

String.split([separator]) - returns array of substrings that was obtained by separating String by separator. If separator is not defined then separator = ","

names = "Artem,Michail,Nicholas,Alexander";
listOfNames = names.split(','); //Split string to list of strings
twoNames = names.split(',',2); //Split with limit

Getting substrings and char

edit

We can get a substring from a string using the substr(index,len) and substring(indexA,indexB) methods. First returns the substring from 'index' with length equal to len. Second returns the substring from indexA to indexB.

a = "Hello world!";
first = a.substr(0,5); //Hello
second = a.substring(6,11); // world

We can also get a char at some position using charAt function.

a = "Hello world!";
b = a.charAt(2); //e

Position of substring

edit

We can also get a position of some substring in a string using the indexOf and lastIndexOf methods. Both functions have two arguments but only the first is required: the string to be searched and the position from that the string is searched. indexOf returns the first position of the substring and lastIndexOf returns the last position of the substring. If the substring is not found both functions return -1.

a = "Hello world";
b = a.indexOf('o',5); // 7
c = a.lastIndexOf('l'); // 9

Data types - Arrays · Data types - Objects