The JavaScript string is an object that represents a sequence of characters, each identified by one index.
Creation:
To create strings in JavaScript, you use either single quotes or double quotes like this:
let str = 'Hi';
let greeting = "Hello";
'Hi' and "Hello" are called a string literals. A string literal, or string, is a series of zero or more characters enclosed in single or double quotes.
Accessing characters:
To access the characters in a string, you use the array-like [] notation with the zero-based index.
The following example returns the first character of a string with the index zero:
let str = "Hello";
console.log(str[0]); // "H"
Getting the length:
We can get the length of a string using the .length property.
For example, to access the last character of the string, you use the length - 1 index:
let str = "Hello";
console.log(str[str.length - 1]); // "o"
Concatenating strings via + operator:
To concatenate two or more strings, you use the + operator:
let name = 'John';
let str = 'Hello ' + name;
console.log(str); // "Hello John"
If you want to assemble a string piece by piece, you can use the += operator:
let greet = 'Welcome';
let name = 'John';
greet += ' to AlgoCademy, ';
greet += name;
console.log(greet); // "Welcome to AlgoCademy, John"
String slicing
We often want to get a substring of a string. For this, we use the slice() method.
slice(startIndex, endIndex) returns the substring from startIndex to endIndex:
let str = 'JavaScript';
let substr = str.slice(2, 6);
console.log(substr); // "vaSc"
The startIndex is a zero-based index at which the slice() start extraction.
The endIndex is also zero-based index before which the slice() ends the extraction. The substr will not include the character at the endIndex index.
If you omit the endIndex, the slice() extracts to the end of the string:
let str = 'JavaScript';
let substr = str.slice(4);
console.log(substr); // "Script"
String Immutability:
In JavaScript, String values are immutable, which means that they cannot be altered once created.
For example, the following code:
let myStr = "Bob";
myStr[0] = 'J';
cannot change the value of myStr to "Job", because the contents of myStr cannot be altered.
Note that this does not mean that myStr cannot be changed, just that the individual characters of a string literal cannot be changed. The only way to change myStr would be to assign it with a new string, like this:
let myStr = "Bob";
myStr = "Job";
//or
myStr = 'J' + myStr.slice(1, 3);
The split function
The split() method splits (divides) a string into two or more substrings depending on a splitter (or divider). The splitter can be a single character, another string, or a regular expression.
After splitting the string into multiple substrings, the split() method puts them in an array and returns it. It doesn't make any modifications to the original string.
This splitter is provided as an argument in the split() function. For example:
let str = "I am happy!";
let myArr = str.split(" ");
console.log(myArr); // ['I', 'am', 'happy!']
Convert a string to an array of characters:
When we have to change characters often in a string, we want a way of doing this quickly. Because strings are immutable, we change a character by creating a whole new string, which is O(n).
But arrays are mutable and chaning an element in an array is O(1). So what we can do is first convert our string to an array of characters, operate on that array and than convert the array back to a string.
We can convert a string to an array using the split() method with an empty splitter (''), like this:
let str = "Andy";
let myArr = str.split('');
console.log(myArr); // ['A', 'n', 'd', 'y']
myArr[0] = 'a';
myArr[2] = 'D';
// We convert an array of chars to a string with join():
str = myArr.join('');
console.log(str); // "anDy"
Iterating through the characters:
We can iterate throught the characters of a string using a for loop and the of keyword like this:
var myStr = "Andy";
for (let c of myStr) {
console.log(c);
}
// This will print the characters 'A', 'n', 'd' and 'y' on different lines
We can also iterate throught the elements of a string using indices and a for loop like this:
var myStr = "Andy";
for (let i = 0; i < myStr.length; i++) {
console.log(myStr[i]);
}
// This will print the characters 'A', 'n', 'd' and 'y' on different lines
Both ways take O(n) time, where n is the length of the array we iterate on.
Assignment
Follow the Coding Tutorial and let's play with some arrays.
Hint
Look at the examples above if you get stuck.
Free plan: 30 tutor messages. PRO is unlimited.
