In this tutorial, we will learn about strings in JavaScript. We will cover the basics of string manipulation, including creating, accessing, modifying, and performing operations on strings.
A string in JavaScript is a sequence of characters. Strings are immutable, meaning their values cannot be changed once created. Strings are used for storing and handling text data.
Strings can be created in JavaScript using single or double quotes:
let str = "Hello, world!";
Strings can also be created using backticks for template literals:
let str2 = `Hello, world!`;
console.log
.let str = "Hello, world!";
console.log(str);
Hello, world!
charAt
method.let str = "Hello";
console.log(str[0]); // Accessing using array indexing
console.log(str.charAt(1)); // Accessing using charAt()
H e
let str = "Hello";
str = 'J' + str.substring(1); // Modifying individual character
str += " World!"; // Appending new characters
console.log(str);
Jello World!
+
operator or template literals.let str1 = "Hello";
let str2 = " World!";
let str3 = str1 + str2; // Concatenating strings
console.log(str3);
Hello World!
indexOf
method to find a substring.let str = "Hello, world!";
let pos = str.indexOf("world"); // Finding substring
if (pos !== -1) {
console.log("Found 'world' at position: " + pos);
} else {
console.log("Substring not found");
}
Found 'world' at position: 7
length
property to get the length of the string.let str = "Hello, world!";
console.log("Length of the string: " + str.length);
Length of the string: 13