JavaScript Strings
Subject: JavaScript
In JavaScript, a string is a sequence of characters used to represent text. Strings are a core data type and are enclosed in single quotes (' '), double quotes (" "), or backticks ( ) for template literals.
What is a String in JavaScript?
A string can include letters, numbers, symbols, or spaces. Strings are immutable, meaning once created, they can't be changed—any operation returns a new string.
Creating Strings
1. Using String Literals
2. Using String Constructor (Not Recommended)
Use string literals for better performance and readability.
Common String Methods in JavaScript
1. .length
Returns the number of characters in the string.
2. .toUpperCase() and .toLowerCase()
3. .charAt(index)
4. .indexOf() and .lastIndexOf()
5. .slice(start, end)
Extracts a section of a string.
6. .substring(start, end)
Similar to slice but doesn’t support negative indexes.
7. .replace()
8. .trim()
Removes whitespace from both ends.
9. .split(separator)
Splits a string into an array.
10. .includes()
Checks if a substring exists.
Template Literals (Backticks `)
Allow embedding variables and expressions:
Escape Characters
Use \ to escape characters like quotes and newlines:
Key Takeaways
- Strings are immutable and used to represent textual data.
- JavaScript offers built-in methods like
slice(),replace(),split(), andtrim(). - Use template literals for string interpolation and multi-line formatting.
- Always prefer string literals over the
Stringconstructor.