JavaScript provides several built-in string methods that are commonly used for manipulating and working with strings. Here are seven frequently used string methods:
1. concat()
The concat() method is used to concatenate two or more strings and returns a new string.
const str1 = 'Hello';
const str2 = 'World';
const result = str1.concat(' ', str2);
// "Hello World"
2. indexOf() and lastIndexOf()
The indexOf() method returns the index of the first occurrence of a specified substring in a string. If the substring is not found, it returns -1. lastIndexOf() works similarly but searches for the last occurrence.
const str = 'Hello World';
const index = str.indexOf('World');
// 6
const lastIndex = str.lastIndexOf('l');
// 9
3. charAt() and charCodeAt():
charAt() returns the character at a specified index in a string. charCodeAt() returns the Unicode value of the character at a specified index.
const str = 'Hello';
const char = str.charAt(1); // "e"
const charCode = str.charCodeAt(1); // 101
4. slice():
The slice() method extracts a portion of a string and returns it as a new string, without modifying the original string.
const str = 'Hello World';
const sliced = str.slice(0, 5); // "Hello"
5. toUpperCase() and toLowerCase():
toUpperCase() converts all characters in a string to uppercase, while toLowerCase() converts them to lowercase.
const str = 'Hello World';
const upper = str.toUpperCase();
//ex "HELLO WORLD"
const lower = str.toLowerCase();
// ex "hello world"
6. replace():
The replace() method is used to replace a specified substring or pattern with another string.
const str = 'Hello World';
const replaced = str.replace('World', 'Universe');
// ex "Hello Universe"
7. split():
The split() method is used to split a string into an array of substrings based on a specified separator.
const str = 'apple,orange,banana';
const fruits = str.split(',');
//ex ["apple", "orange", "banana"]
These are just a few examples, and JavaScript provides many more string methods for various string manipulations. Understanding and mastering these methods can significantly enhance your ability to work with strings in JavaScript.
Post a Comment