4.1 Introduction to Strings
In JavaScript, strings are sequences of characters and are one of the basic data types. You can create strings using single quotes ('text '), double quotes ("text"), or backticks (`text`).
Examples of strings:
let singleQuote = 'Hello, World!';
let doubleQuote = "Hello, World!";
let backticks = `Hello, World!`;
You can call these methods on a string object:
Method | Description |
---|---|
length | Returns the length of the string |
charAt(index) | Returns the character at the specified position |
toUpperCase() | Converts the string to uppercase |
toLowerCase() | Converts the string to lowercase |
indexOf(substring) | Returns the index of the first occurrence of a substring or -1 if not found |
includes(substring) | Checks if the string contains the specified substring, returns true or false |
slice(start, end) | Extracts a part of the string and returns a new string |
replace(searchValue, newValue) | Replaces the specified substring with a new substring |
split(separator) | Splits the string into an array of substrings using the specified separator |
trim() | Removes whitespace from both sides of the string |
4.2 Basic String Methods
Examples of method usage
1. Property length
Returns the length of the string:
let str = 'Hello';
console.log(str.length); // 5
2. Method charAt(index)
Returns the character at the specified position:
let str = 'Hello';
let result = str.charAt(1);
console.log(result); // 'e'
3. Methods toUpperCase() and toLowerCase():
Convert the string to uppercase or lowercase:
let str = 'Hello';
console.log(str.toUpperCase()); // 'HELLO'
console.log(str.toLowerCase()); // 'hello'
4. Method indexOf(substring)
Returns the index of the first occurrence of a substring or -1 if the substring is not found:
let str = 'Hello, world!';
let result = str.indexOf('world');
console.log(result); // 7
5. Method includes(substring)
Checks if the string contains the specified substring, returns true or false:
let str = 'Hello, world!';
let result = str.includes('world');
console.log(result); // true
6. Method trim()
Removes whitespace from both sides of the string:
let str = ' Hello, world! ';
console.log(str.trim()); // 'Hello, world!'
7. Method replace(searchValue, newValue)
Replaces the specified substring with a new substring:
let str = 'Hello, world!';
console.log(str.replace('world', 'JavaScript')); // 'Hello, JavaScript!'
8. Method split(separator)
Splits the string into an array of substrings using the specified separator:
let str = 'Hello, world!';
let words = str.split(' ');
console.log(words); // ['Hello,', 'world!']
9. Method substring(start, end)
Returns the substring between two indices:
let str = 'Hello, world!';
console.log(str.substring(0, 5)); // 'Hello'
10. Method substr(start, length)
Returns a substring starting from the specified index and extending for a given number of characters:
let str = 'Hello, world!';
console.log(str.substr(0, 5)); // 'Hello'
11. Method slice(start, end)
Extracts a part of the string and returns a new string:
let str = 'Hello, world!';
console.log(str.slice(0, 5)); // 'Hello'
12. Method startsWith(substring)
Checks whether the string starts with the specified substring, returns true
or false
:
let str = 'Hello, world!';
console.log(str.startsWith('Hello')); // true
13. Method endsWith(substring)
Checks whether the string ends with the specified substring, returns true
or false
:
let str = 'Hello, world!';
console.log(str.endsWith('world!')); // true
14. Method repeat(count)
Returns a new string containing the specified number of copies of the original string:
let str = 'Hello';
console.log(str.repeat(3)); // 'HelloHelloHello'
let str2 = '-';
console.log(str2.repeat(30)); // '---------------------------------------------------------------'
4.3 Next-Gen Strings
Template strings were added to JavaScript recently. They provide a more convenient and readable way to work with text compared to regular strings. They are enclosed in backticks (`) and support expression interpolation and multiline text.
Syntax:
`next-generation string`
Example:
A template literal greeting
is created using backticks.
const greeting = `Hello, World!`;
console.log(greeting); // "Hello, World!"
Main features of template strings:
- Expression interpolation: template strings allow you to insert expressions and variables inside the string using
${}
- Multiline text: template strings support multiline text without the need to use special characters for line breaks
- Embedded expressions: you can use any JavaScript expressions inside template strings, including functions
Let's look at some examples of using template strings.
Expression Interpolation
Template strings make it easy to insert variable values and expression results inside the string:
let name = "Alice";
let age = 30;
let greeting = `Hello, ${name}! You are ${age} years old.`;
console.log(greeting); // "Hello, Alice! You are 30 years old."
In this example, the variables name
and age
are inserted inside the string using ${}
.
Multiline Text
Template strings make it easier to create multiline strings without the need to use
line break characters (\n
):
let multiLine = `Lorem ipsum odor, consectetuer adipiscing elit.
Sit lorem mattis eget maximus.`;
console.log(multiLine);
Embedded Expressions
You can use any JavaScript expressions inside template strings, including function calls:
let a = 5;
let b = 10;
let result = `The sum of ${a} and ${b} is ${a + b}.`;
console.log(result); // "The sum of 5 and 10 is 15."
function getGreeting(name) {
return `Hello, ${name}!`;
}
let greeting = `${getGreeting("Bob")}`;
console.log(greeting); // "Hello, Bob!"
Sure, it's better not to call functions inside strings, but if you really want to, you can.
GO TO FULL VERSION