About Lesson
JavaScript Strings
A string in JavaScript is a sequence of characters, enclosed within single quotes (''
) or double quotes (""
).
Creating Strings
You can create strings using either single or double quotes.
Example:
const singleQuotedString = 'Hello, world!';
const doubleQuotedString = "Hello, world!";
String Methods
JavaScript provides various methods for working with strings, such as:
length:
Returns the length of the string.toUpperCase():
Converts the string to uppercase.toLowerCase():
Converts the string to lowercase.charAt(index):
Returns the character at the specified index.indexOf(substring):
Returns the index of the first occurrence of the specified substring.substring(startIndex, endIndex):
Returns the substring between the specified indices.split(separator):
Splits the string into an array of substrings based on the specified separator.replace(searchValue, replaceValue):
Replaces occurrences of a specified value with another value.
Example:
const str = "Hello, world!";
console.log(str.length); // Output: 13
console.log(str.toUpperCase()); // Output: HELLO, WORLD!
console.log(str.indexOf("world")); // Output: 7
console.log(str.substring(7)); // Output: world!
console.log(str.split(", ")); // Output: ["Hello", "world!"]
console.log(str.replace("world", "John")); // Output: Hello, John!
String Concatenation
You can concatenate strings using the +
operator or the concat()
method.
Example:
const firstName = "John";
const lastName = "Doe";
const fullName = firstName + " " + lastName;
console.log(fullName); // Output: John Doe
Strings are fundamental data types in JavaScript and are used extensively for storing and manipulating text-based data. Understanding string methods and operations is crucial for effective string manipulation in JavaScript.