Strings in JavaScript
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.
What is a String
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.
Creating Strings
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!`;
Example 1: Initializing Strings
- Create a string variable and initialize it with a value.
- Print the string variable using
console.log
.
JavaScript Program
let str = "Hello, world!";
console.log(str);
Output
Hello, world!
Example 2: Accessing Characters in a String
- Create a string variable and initialize it with a value.
- Access and print individual characters using array indexing or the
charAt
method.
JavaScript Program
let str = "Hello";
console.log(str[0]); // Accessing using array indexing
console.log(str.charAt(1)); // Accessing using charAt()
Output
H e
Example 3: Modifying Strings
- Create a string variable and initialize it with a value.
- Strings in JavaScript are immutable, so create a new string with the modified value.
- Print the modified string.
JavaScript Program
let str = "Hello";
str = 'J' + str.substring(1); // Modifying individual character
str += " World!"; // Appending new characters
console.log(str);
Output
Jello World!
Example 4: String Concatenation
- Create two string variables and initialize them with values.
- Concatenate the strings using the
+
operator or template literals. - Print the concatenated string.
JavaScript Program
let str1 = "Hello";
let str2 = " World!";
let str3 = str1 + str2; // Concatenating strings
console.log(str3);
Output
Hello World!
Example 5: Finding Substrings
- Create a string variable and initialize it with a value.
- Use the
indexOf
method to find a substring. - Print the position of the found substring.
JavaScript Program
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");
}
Output
Found 'world' at position: 7
Example 6: String Length
- Create a string variable and initialize it with a value.
- Use the
length
property to get the length of the string. - Print the length of the string.
JavaScript Program
let str = "Hello, world!";
console.log("Length of the string: " + str.length);
Output
Length of the string: 13