String
A string in JavaScript is a sequence of characters used to represent text. It can be letters, numbers, symbols, or a combination of these. Strings are enclosed in either single quotes (') or double quotes ("), and can also be created using template literals with backticks (`).
//Example
let singleQuoteString = 'Hello, World!';
let doubleQuoteString = "JavaScript is fun!";
let name = 'Alice';
let templateLiteralString = `Hello, ${name}! Welcome to JavaScript.`;
let numberString = '12345';
let multilineString = `This is a
multiline string in JavaScript.`;
Both single (') and double (") quotes are used to define strings. They behave the same but the important rule is that the opening and closing quotes must match—meaning, if you start a string with a single quote, you must end it with a single quote, and the same goes for double quotes.
//Correct
let str1 = 'Hello, World!';
let str2 = "JavaScript is fun!";
//Incorrect
let str3 = "Hello, World!';
let str4 = "JavaScript is fun!';
But if you want to use single quote or double quote in a string then you can enclose it in double quotes to avoid needing an escape character, and vice versa or use escape characters (\' or \"). For example:
let str3 = "It's a sunny day.";
let str4 = 'He said, "Hello!"';
let str5 = 'It\'s a sunny day.';
let str6 = "He said, \"Hello!\"";
Escape characters in JavaScript are used to allow special characters within strings that would otherwise be treated differently or cause errors. By using an escape character, we can tell JavaScript to treat the next character as a regular part of the string, rather than its usual meaning in the code. Common escape characters:
- \': Single quote
- \": Double quote
- \\: Backslash
- \n: New line
- \t:Tab
- \r: Carriage return
- \b: Backspace
- \f: Form feed
let escapeExample = 'I\'m learning JavaScript.\nIt\'s fun!';
let text = "He said, \"JavaScript is awesome!\" \nAnd I couldn't agree more.";
console.log(text);
// Output:
// I'm learning JavaScript.
// It's fun!
// He said, "JavaScript is awesome!"
// And I couldn't agree more.
A literal in programming is simply a fixed value written directly in the code, like a number, string, or boolean. It's the actual data you type, not a variable or expression. A string literal is a sequence of characters enclosed in single ('), double ("), or backticks (`) directly written in your code to represent text.
let str = 'Hello World';
let funStr = "JavaScript is fun";
We typically use string literals instead of string objects because string literals are simpler, more efficient, and easier to work with. We will discuss string comparison in more detail later in this tutorial.
The length property in JavaScript returns the number of characters in a string, including spaces and special characters. In the below example, the length property returns 11 because "Hello World" contains 11 characters, including the space.
let text = 'Hello World';
console.log(text.length); // Output: 11
console.log(text.length()); //wrong
Note: length is a property, not a function.
A string in JavaScript is a primitive data type, representing a sequence of characters. It is immutable, meaning that once a string is created, its content cannot be changed directly. JavaScript treats a string like an array of characters for the purpose of indexing. This means you can use square bracket notation ([]) with an index to access a specific character in a string.
const str = "hello";
console.log(str[0]); // Output: 'h'
console.log(str[4]); // Output: 'o'
JavaScript allows looping over strings using loops like for...of and for loops, similar to how we iterate over arrays. The for...of loop iterates directly over each character in the string.
const str = "hello";
for (const char of str) {
console.log(char);
}
// Output:
// h
// e
// l
// l
// o
Unlike arrays, strings in JavaScript are immutable. This means that once a string is created, its characters cannot be changed directly. If you need to modify a string, you must create a new one.
let str = "hello";
// Attempting to change a character (this won't work)
str[0] = "H";
console.log(str); // Output: 'hello'
// To change it, create a new string
str = "H" + str.slice(1);
console.log(str); // Output: 'Hello'
A method is a function that is associated with an object or a class. It operates on the data (properties) within that object and is called using the object's name. String methods are built-in functions that perform operations on string values, such as modifying, searching, or converting strings. Here is an explanation of string methods in alphabetical order with examples and syntax:
-
charAt() -
Returns the character at a specified index in a
string.
//Syntax: string.charAt(index) //Example let text = 'Hello'; console.log(text.charAt(1)); // Output: 'e'
-
concat() - Joins
two or more strings into one.
//Syntax: string.concat(string2, string3, ...) //Example let str1 = 'Hello'; let str2 = 'World'; console.log(str1.concat(' ', str2)); // Output: 'Hello World'
-
endsWith() -
Checks if a string ends with a specified substring.
//Syntax: string.endsWith(searchString) //Example let text = 'Hello World'; console.log(text.endsWith('World')); // Output: true
-
includes() -
Checks if a string contains a specified value.
//Syntax: string.includes(searchString) //Example let text = 'Hello World'; console.log(text.includes('World')); // Output: true
-
indexOf() -
Returns the index of the first occurrence of a
specified value. If not found, it returns -1.
//Syntax: string.indexOf(searchValue) //Example let text = 'Hello World'; console.log(text.indexOf('World')); // Output: 6
-
lastIndexOf() -
Returns the index of the last occurrence of a
specified value. If not found, returns -1.
//Syntax: string.lastIndexOf(searchValue) //Example let text = 'Hello World World'; console.log(text.lastIndexOf('World')); // Output: 12
-
match() -
Searches a string for a match against a regular
expression and returns the matches.
//Syntax: string.match(regex) //Example let text = 'The rain in Spain stays mainly in the plain'; console.log(text.match(/ain/g)); // Output: ['ain', 'ain', 'ain']
Note: Regex (Regular Expression) is a sequence of characters that defines a search pattern, primarily used for matching, searching, and manipulating text.
-
padEnd() - Pads
the current string from the end with another string
until it reaches the desired length.
//Syntax: string.padEnd(targetLength, padString) //Example let text = 'Hello'; console.log(text.padEnd(8, '!')); // Output: 'Hello!!!'
-
padStart() -
Pads the current string from the beginning with
another string until it reaches the desired length.
//Syntax: string.padStart(targetLength, padString) //Example let text = '5'; console.log(text.padStart(3, '0')); // Output: '005'
-
repeat() -
Repeats the string a specified number of times.
//Syntax: string.repeat(count) //Example let text = 'Hi '; console.log(text.repeat(3)); // Output: 'Hi Hi Hi '
-
replace() -
Replaces a specified value with another value in a
string.
//Syntax: string.replace(searchValue, newValue) //Example let text = 'Hello World'; console.log(text.replace('World', 'JavaScript')); // Output: 'Hello JavaScript'
-
search() -
Searches a string for a match using a regular
expression and returns the index of the match.
//Syntax: string.search(regex) //Example let text = 'Hello World'; console.log(text.search(/World/)); // Output: 6
-
slice() -
Extracts a part of a string and returns it as a new
string.
//Syntax: string.slice(start, end) //Example: let text = 'Hello World'; console.log(text.slice(0, 5)); // Output: 'Hello'
-
split() -
Splits a string into an array of substrings based on
a specified delimiter.
//Syntax: string.split(separator) //Example: let text = 'a,b,c'; console.log(text.split(',')); // Output: ['a', 'b', 'c']
-
startsWith() -
Checks if a string starts with a specified
substring.
//Syntax: string.startsWith(searchString) //Example: let text = 'Hello World'; console.log(text.startsWith('Hello')); // Output: true
-
substring() -
Checks if a string starts with a specified
substring.
//Syntax: string.substring(start, end) //Example: let text = 'Hello World'; console.log(text.substring(0, 5)); // Output: 'Hello'
-
toLowerCase() -
Converts a string to lowercase.
//Syntax: string.toLowerCase() //Example: let text = 'Hello World'; console.log(text.toLowerCase()); // Output: 'hello world'
-
toUpperCase() -
Converts a string to uppercase.
//Syntax: string.toUpperCase() //Example: let text = 'hello world'; console.log(text.toUpperCase()); // Output: 'HELLO WORLD'
-
trim() -
Removes whitespace from both ends of a string.
//Syntax: string.trim() //Example: let text = ' Hello World '; console.log(text.trim()); // Output: 'Hello World'
-
trimEnd() -
Removes whitespace from the end of a string.
//Syntax: string.trimEnd() //Example: let text = 'Hello World '; console.log(text.trimEnd()); // Output: 'Hello World'
-
trimStart() -
Removes whitespace from the beginning of a string.
//Syntax: string.trimStart() //Example: let text = ' Hello World'; console.log(text.trimStart()); // Output: 'Hello World'
-
valueOf() -
Returns the primitive value of a string object.
//Syntax: string.valueOf() //Example: let strObj = new String('Hello'); console.log(strObj.valueOf()); // Output: 'Hello'
String Introduction:
- A string is a sequence of characters used to represent text in JavaScript.
- A sequence of characters used for text, enclosed in single quotes ('), double quotes ("), or template literals with backticks (`).
Quotes:
- Use ' or " for strings; the opening and closing quotes must match.
Escape Characters:
- Escape sequences start with a backslash (\) and allow inclusion of special characters. Example: \n, \', \"
String Literal:
- The .length property returns the total number of characters, including spaces and special characters.
String & Array:
- Strings are indexed like arrays, allowing character access using [index].
String Immutability:
- Once a string is created, its content can't be altered; instead, a new string must be created.
String Methods:
- JavaScript provides numerous methods for strings, like .toUpperCase() to convert to uppercase, .slice() to extract parts, and .split() to break a string into an array.
- These methods do not alter the original string but return a new modified version because of string immutability.
- What is a string in JavaScript?
- What are the different ways to create strings in JavaScript?
- How do you convert a number to a string in JavaScript?
- How do you convert a string to a number in JavaScript?
- What is the difference between == and === when comparing strings?
- How can you check if a string contains a specific substring?
- How do you extract a part of a string in JavaScript?
- What is the difference between slice(), substring(), and substr()?
- What are template literals and how are they different from regular strings?
- What is the difference between replace() and replaceAll()?
- How do you check if a string matches a regular expression in JavaScript?
- How do you find the first occurrence of a substring in a string?
- How do you find all occurrences of a substring in a string?
- What are Unicode and UTF-16 in the context of JavaScript strings?
- How do you convert a string to its character code and vice versa?
- How do you iterate through each character of a string?
- What is the difference between charAt() and charCodeAt()?
- What happens when you try to access a character at an index that doesn't exist?
- Is JavaScript string immutable? Explain.
- How do you handle multi-line strings in JavaScript?
- What are some performance considerations when working with strings?
- How do you use regular expressions with strings in JavaScript?
- What is the difference between match() and exec() when dealing with regular expressions?
- How do you check if a string is empty in JavaScript?
- What is a tagged template literal in JavaScript?