We will learn about
- String
- Template Literal
- Escape Characters
- String Methods
String
String is a sequence of characters used to represent text.
There are 2 ways to create string in JavaScript
- By string literal
- By string object (using new keyword)
By string literal
String is created by wrapping the text inside single quotes ('
), double quotes ("
), or backticks (`
).
A string created using single quotes, double quotes, or backticks is generated as a primitive value, similar to numbers and boolean values. Primitive data are immutable, which means they cannot be changed.
Strings created using backticks are also known as template literals and possess special features which we will discuss in a while.
let str = "Welcome to my blog!";
console.log(str);
Output:
Welcome to my blog!
By string object (using new keyword)
let str = new String( "Welcome to my blog!");
console.log(str);
Output:
Welcome to my blog!
Keypoints:
- Do not create Strings objects.
- The
new
keyword complicates the code and slows down execution speed. - String objects can produce unexpected results
- Comparing two JavaScript objects always returns false.
Note: From now on I will discuss exclusively primitive strings.
String indexing
You can access each character inside a string through its numeric index. String indexes are zero-based:
- The first character is in position 0, the second in 1, and so on.
let str = "Google";
console.log(str[0]);
console.log(str[1]);
console.log(str[2]);
console.log(str[3]);
console.log(str[4]);
console.log(str[5]);
Output:
G
o
o
g
l
e
Template literals
Before, we said that template literals (strings created with backticks, `
) have some special features. One is the ability to display the text on multiple lines, easy peasy.
let intro = `Welcome to my website.
This is my blog.
We are learning strings.`;
console.log(intro);
Output:
Welcome to my website.
This is my blog.
We are learning strings.
The output text mirrors the spacing used to write the string. That would not have been the case for other literal strings, which require the use of a newline character, \n
, in order to have the text arranged in a multi-line fashion.
If we want to include a variable inside a string created with single or double quotes, you should make use of comma or addition operator, as seen before.
let obj = {
item: "pen",
cost: 10,
};
console.log("The cost of", obj.item, "is", obj.cost, "rupees.");
Output:
The cost of pen is 10 rupees.
But template literals provide a feature called string interpolation, that simplifies the readability and makes the code more fluid.
String interpolation allows injecting variables, function calls, and arithmetic expressions directly into a string.
Syntax:
`string text ${expression} string text`
Here’s the previous example rewritten with template literals:
let obj = {
item: "pen",
cost: 10,
};
console.log(`The cost of ${obj.item} is ${obj.cost} rupees.`)
Output:
The cost of pen is 10 rupees.
We can also add expressions in template literal. Template literal allows both single and double quotes inside a string
console.log(`Sum of first 3 "natural numbers" is ${1 + 2 + 3}`);
Output:
Sum of first 3 "natural numbers" is 6
To sum up template literal, we can say template literal allows
- multiline strings
- variables in strings
- expressions in strings
- both single and double quotes inside a string
Escape Characters
Escape characters are special sequences used to represent characters that would otherwise be interpreted differently by the interpreter.
Here are some commonly used escape sequences in JavaScript:
\
– Backslash\n
– Newline\t
– Tab
Let’s say we want to print My name is "Tony"
, we have to write
console.log("My name is "Tony"");
Here we are writing Tony
in double quotes. Interpretor (program which runs our code) will read the string written inside first double quotes "My name is "
and rest of the part Tony""
will be missed as it will generate a syntax error because we need comma or addition operator to join two strings.
Output:
Uncaught SyntaxError: missing ) after argument list
So we use escape character “\” to write something like this.
console.log("My name is \"Tony\""); //Double quotes
console.log('My name is \'Stark\''); //Single quotes
Output:
My name is "Tony"
My name is 'Stark'
We use \n to add new line to the string.
console.log("My first name is Tony\nMy last name is Stark.");
Output:
My first name is Tony
My last name is Stark.
We use \t to add more space in the string.
console.log("My first name is Tony Stark");
console.log("My first name is Tony\tStark");
Output:
My first name is Tony Stark
My first name is Tony Stark
String Methods
Methods are built-in functions to manipulate strings.
Let’s say we want to change a string.
For example
let str = "Hello";
str[0] = "y"; // 'H' should be changed to 'y'
console.log(str);
Strings can not be changed because they are immutable.
Output:
Hello
Whenever we make a change in string, it is not reflected in the original string. Rather, a new string is returned and stored in the variable. That is why we use methods to manipulate string because they return new string.
There are many string methods. Some of the most common methods are given below.
String length
Returns the number of characters in a string.
let text = "Hello World!";
console.log(text.length);
Output:
12
String concat()
Joins two or more strings together.
let text1 = "Hello";
let text2 = " World!";
console.log(text1.concat(text2));
Output:
Hello World!
We can also concatenate string with comma or addition operator
console.log(text1 + text2);
Output:
Hello World!
String toUpperCase()
Returns uppercase of a string.
let text = "Hello World!";
console.log(text.toUpperCase());
Output:
HELLO WORLD!
String toLowerCase()
Returns lowercase representation of a string.
let text = "Hello World!";
console.log(text.toLowerCase());
Output:
hello world!
String trim()
Removes whitespace from both ends of a string.
let text = " Hello World! ";
console.log(text.trim());
Output:
Hello World!
String slice()
Extracts and returns a section of the string.
let text = "Hello World!";
console.log(text.slice(0,5));
Output:
Hello
String replace()
replace a substring/pattern in the string
let text = "Hello";
console.log(text.replace("H","y"));
Output:
yello
String replaceAll()
replace() only replaces the first matching substring/pattern.
replaceAll() replaces all substring/pattern.
let text = "Hellololo";
console.log(text.replaceAll("lo","p"));
Output:
Helppp
Leave a Reply