String methods
A string is a sequence of characters wrapped in either single quotes, double quotes or backticks. Strings are primitive data types and they are immutable. Immutability means that once a string is created, it cannot be changed.
split()
Splits the string into an array of substrings. The method takes a pattern and divides this string into an ordered list of substrings by searching for the pattern, puts these substrings into an array, and returns the array.
const userName = 'Joe Doe';
console.log(userName.split(' '));
// expected output: ["Joe", "Doe"]
console.log(usernam.split(''));
// expected output: ['J', 'o', 'e', ' ', 'D', 'o', 'e']
function getInitials(name) {
return name
.split(' ')
.map(word => word[0].toUpperCase())
.join('');
}
getInitials('Joe Doe'); // "JD"
"The Shining | King, Stephen | 1977 | Shelf K1".split("|")
// ["The Shining ", " King, Stephen ", " 1977 ", " Shelf K1"]
indexOf()
A substring is a sequence of characters that appears within a larger string. For example, in the string "hello world", "hello" and "world" are substrings.
The indexOf() method is used to find the position (index) of a specific element inside a string or array. If it’s not found, it returns -1
const text = "JavaScript is amazing";
console.log(text.indexOf("Script")); // 4
Is case sensitive
function findSubstring(sentence, substring) {
return sentence.indexOf(substring);
}
console.log(findSubstring("Peter Parker is Spiderman", "Spiderman")); // 16
console.log(findSubstring("JavaScript is cool", "Cool")); // -1
The indexOf() method takes two arguments: the first is the substring you want to find within the larger string, and the second is an option starting position for the search.
let sentence = "JavaScript is awesome, and JavaScript is powerful!";
let position = sentence.indexOf("JavaScript", 10);
console.log(position); // 27
Another use case
const input = "Learn JavaScript and understand frameworks";
const term = "JavaScript";
if (input.indexOf(term) !== -1) {
console.log(`The term "${term}" exists in the sentence.`);
}
slice()
The slice() method extracts a section of a string. It takes two arguments: the start index (included) and the end index (not included).
const sentence = "Welcome to Berlin!";
const city = sentence.slice(11, 17);
console.log(city);
// expected output: Berlin
The slice() method can use negative indices to count from the end of the string. -1 refers to the last character.
const text = "JavaScript";
const lastThree = text.slice(-3);
console.log(lastThree);
// expected output: ipt
replace()
Method which is used to locate a substring in a string and replace it with another value. Remember that strings are immutable which means the original text is not modified in that example. A new string is created instead
const originalString = "Cats are lovely";
const replacedString = originalString.replace("Cats", "Dogs");
console.log(replacedString);
// expected output: Dogs are lovely
Like other string methods this one is case sensitive. In the next example, the original string to be replaced is in lowercase and the return value will be an empty string.
const originalString = "Cats are lovely";
const lowerCaseString = originalString.toLowerCase();
const replacedString = originalString.replace(lowerCaseString, "Dogs");
console.log(replacedString);
// expected output:
To replace all ocurrences you should use replaceAll() method.
const exampleSentence = "I love cats and cats are so much fun!";
const dogsOnlySentence = exampleSentence.replaceAll("cats", "dogs");
console.log(dogsOnlySentence);
// espected output: I love dogs and dogs are so much fun!
const learningSentence = "I love learning!";
const love = learningSentence.slice(2, 7);
const repeatedLove = love.repeat(3);
console.log(repeatedLove);
// expected output: love love love