Strings
Strings are text in quotation marks - single quotes (' '
) double quotes (" "
), or backtick quotes.
See the example below:
const str1 = 'This is a text in the single quote.';
const str2 = "This is a text in double-quotes.";
const str3 = `This is a text in backticks quotes.`;
Strings also includes pretty nice methods like includes('...')
, indexOf('...')
, etc.
const str = 'This is a text in the single quote.';
str.includes('text'); // true
The internal format for strings is always UTF-16
String Template Literals
Backticks are best used for template literals.
The syntax for the template literals is shown below:
`... ${expression} ...`
See the example below:
const myName = (fName, lName) => {
return fName + ' ' + lName;
};
console.log(`His name is ${myName('Osagie', 'Bello').}`);
// His name is Osagie Bello.
String in Multi-lines
Text in backtick can easily span multiple lines.
See the example below:
const str = `Hello World!
My name is:
Last Name - Bello
FirstName - Osagie`;
console.log(str);
/*
Hello World!
My name is:
Last Name - Bello
FirstName - Osagie
*/
Alternatively, the newline character \n
can be used to escape to a new line.
See the example below:
const str = 'Hello World!\nMy name is:\nLast Name - Bello\nFirstName - Osagie';
console.log(str);
/*
Hello World!
My name is:
Last Name - Bello
FirstName - Osagie
*/
Instead of having all text in a single line, you can escape to a new line with the \
.
See the example below:
const str = 'Hello World!\n\
My name is:\n\
Last Name - Bello\n\
FirstName - Osagie';
console.log(str);
Quotes in String
It is possible to insert quotes in a string.
See the example below:
const str1 = 'Martin Luther King once said "The time is always right to do what is right". 🤔';
const str2 = "Martin Luther King once said \"The time is always right to do what is right\". 🤔";
const str3 = `Martin Luther King once said "The time is always right to do what is right". 🤔`;
const str4 = 'It\'s my birthday. 😁';
const str5 = `It's my birthday. 😁`;
Only the quotes that are the same as the enclosing ones need to be escaped.
MDN contains the complete list of escape characters.
String Length
The string length is the number of characters in a word or sentence (including space).
The syntax is:
str.length
See the example below:
'Hello World'.length; // 11
'Hello\nWorld'.length; // 11'
Escape characters, spaces are all special characters included in the
.length
count.
Accessing Characters
The zero-based index is used to access characters in a string.
str[numPos]
The numPos
is in a zero-based index position.
See the example below:
const str = `Hello World`;
// the first character
console.log( str[0] ); // H
// the fifth character
console.log( str[4] ); // o
Alternatively, the charAt(...)
method can be used
str.charAt(numPos)
See the example below:
const str = `Hello World`;
// the first character
console.log( str.charAt(0) ); // H
// the fifth character
console.log( str.charAt(4) ); // o
The easy way to access characters counting from the last index is to use the length
number property.
str[str.length-N] // N = 1, 2,...
str.charAt(str.length-N) // N = 1, 2,...
See the example below:
const str = `Hello World`;
console.log( str.charAt(str.length-1) ); // d
console.log( str[str.length-1] ); // d
The above example is the same as below:
console.log( str.slice(-1) ); // d
Looping String characters
Iteration can be performed on string characters using
for..of
for (let char of "Hello") {
console.log(char);
/*
H
e
l
l
o => char is now o
*/
char === 'H' // false
char === 'e' // false
char === 'l' // false
char === 'o' // true
},
Immutable Strings
Once a string is created, it can't be changed
const myName = 'Bello';
myName[2] = 'y';
console.log( myName, myName[2] ); // Bello l
You can use the replace method replace(...)
to replace part a string.
The syntax is shown below:
str.replace(oldStr, newStr)
See the examples below:
const myName = 'Bello';
const newName = myName.replace('Bello', 'Beylo');
console.log( newName, newName[2] ); // Beylo y
const str = "I love front-end web development"
const newStr = str.replace('front', 'back');
console.log(newStr);
String Methods
There are a couple of ways to use a method on a string.
See the example below of some built-in method:
let str = 'Bello';
console.log( str.toUpperCase() ); // BELLO
console.log( str.toLowerCase() ); // bello
str = 'bello';
console.log( str[0].toUpperCase(), str ); // B bello
str = 'Hello Bello';
console.log( str.startsWith("Hel") ); // true
console.log( str.endsWith("ello") ); // true
console.log( str.endsWith("Bell") ); // false
str = '#DevCommunity';
console.log( str.startsWith("#Dev") ); // true
console.log( str.endsWith("unity") ); // true
str = 'JavaScript is one of the best programming languages';
console.log( str.indexOf('Script') ); // 4 => S is defined in Script
console.log( str.indexOf('script') ); // -1 => s is undefined in script
str = 'name1, name2, name3, name4,... nameN';
const name = 'name';
console.log(`The index of the first "${name}"
from the end of the string is ${str.lastIndexOf(name)}`);
/*
The index of the first "name"
from the end of the string is 31
*/
console.log(`The index of the first "${name}"
from the start of the string is ${str.indexOf(name)}`);
/*
The index of the first "name"
from the start of the string is 0
*/
str.includes('name3'); // true
const row = 'row, ';
const boat = 'boat...';
str = `${row.repeat(3)}the ${boat.repeat(1)}🎶`;
console.log(str); // row, row, row, the boat...🎶
str = 'Longest word: pneumonoultramicroscopicsilicovolcanoconiosis'
console.log( str.slice(0, 20) );
// Longest word: pneumo => 0 to 19, 20 not included
str = 'Bello Osagie';
console.log( str.slice(6) );
// Osagie => same as (str.slice(6, str.length) )
str = "stringify";
console.log( str.slice(-4, -1) ) // gif
console.log( str.substring(2, 6) ) // ring
console.log( str.slice(2, 6) ) // ring
console.log( str.slice(2, 6) ) // ring
console.log( str.substr(2, 4) ); // ring
str.substr(-4, 2); // gi
console.log( str.substring(2, 6) === str.substring(6, 2) ) // true
console.log( str.slice(2, 6) === str.slice(6, 2) ) // false
const greeting = ' Hello world! ';
console.log(greeting.trim()); // Hello world!;
str = '6';
console.log(str.padStart(2, '0')); // 06
console.log(str.padStart(3, '0')); // 006
console.log(str.padStart(3, '1')); // 116
const accountNum = '168939002125581';
const last4Digits = accountNum.slice(-4);
const encrypt = last4Digits.padStart(accountNum.length, '*');
console.log(encrypt); // ************5581
console.log( `confirm your account number: ${encrypt}` );
// confirm your account number: ************5581
MDN contains the complete list of string methods.
method | selects | negative |
---|---|---|
slice(start, end) |
from start to end (not including end ) |
allows negatives |
substring(start, end) |
between start and end
|
negative values mean 0
|
substr(start, length) |
from start get length characters |
allows negative start
|
Iterable Strings
A String is iterable because it is a collection of characters. It iterates over each character in a string.
See the example below:
const myString = 'Bello Osagie';
for (let char = 1; char <= myString.length-1; char++) {
console.log(myString[char]);
}
/*
B
e
l
l
o
O
s
a
g
i
e
*/
An alternative approach is to use for...in
.
The example above is the same as below:
const myString = 'Bello Osagie';
for (let char in myString) {
console.log(myString[char]);
}
We can also use for...of
to loop through each character in a string.
const myString = 'Bello Osagie';
for (let char of myString) {
console.log(char);
}
The
for...of
is faster thanfor...in
when iterating only characters.
Happy coding!!!
Top comments (0)