04. BASICS | Strings in JavaScript
This article will talk about javascript strings.
let name = 'Shubham'; // string created using single quote
let name = "Shubham"; // string created using double quote
Strings are immutable. We can't modify the string at the same memory address. The modified string will be created at the new memory address.
In order to access the character at an index, we use the following syntax:-
let name = 'shubham';
name[0] // s
name[1] // h
let name = new String('amit');
typeof(name) // Object, not string anymore
/*
0: "a"
1: "m"
2: "i"
3: "t"
*/
Template Literal
Template literal uses backticks instead of quotes to define a string.
let name = `Shubham`; // string created using backticks
With template literal, it is possible to use both single as well as double quotes inside a string.
let sentence = `This is Shubham's book. Title is "JavaScript".`;
We can insert variables directly in template literal. This is called string interpolation.
let name = 'Shubham';
let sentence = `My name is ${name}.`; // Output: My name is Shubham.
Escape Characters
In JavaScript, the backslash (\) is used as the escape character to include special characters in a string that would otherwise be difficult to type or cause syntax errors. The backslash signals to the JavaScript compiler to treat the character(s) that follow it differently.
| Escape Character | What it adds in the string? |
|---|---|
\' |
Single Quote |
\" |
Double Quote |
\\ |
Backslash |
\b |
Backspace |
\f |
Form feed |
\n |
New line |
\r |
Carriage return |
\t |
Horizontal Tabulator |
\v |
Vertical Tabulator |
let text= 'It\'s alright.';
// Output: It's alright.
let text = "We are the so-called \"Vikings\" from the north.";
// Output: We are the so-called "Vikings" from the north.
let text = "The character \\ is called backslash.";
// Output: The character \ is called backslash.
String Properties and Methods
let name = 'Shubham';
name.length // Output: 5
/**NOTE:-
* All the below methods will return the new string.
* Original string(s) will remain unchanged.
**/
let name = 'Shubham';
name.toUpperCase() // Output: SHUBHAM
let name = 'Shubham';
name.toLowerCase() // Output: shubham
let name = 'Shubham';
name.slice(2, 4) // Output: ub (index 4 not included!)
let name = 'Shubham';
name.slice(2) // Output: ubham
let name = 'Shubham Bhai';
name.replace('Bhai', 'Bhau') // Output: Shubham Bhau
let name1 = 'Shubham';
let name2 = 'Agrawal';
name.concat(name2, "25") // Output: Shubham25Agrawal
let name = ' Shubham ';
name.trim() // Output: Shubham
+ operator to concat strings.Happy reading!

