In a previous, we explored JavaScript's array methods, learning how they can help us work with lists of data. If you're just starting, welcome! And if you've been following along, you already know that JavaScript has some incredible tools for us to play with.
Today, we're embarking on a new journey into the world of JavaScript String Methods. Strings are like building blocks for text; these tricks are like magic spells that let us do cool things with them.
In this beginner-friendly guide, we'll dive into the world of strings. We'll learn how to do all sorts of cool stuff with just a few lines of code. You don't need to be a pro β we'll explain everything step by step, with simple examples.
So, whether you're new to coding and want to learn cool JavaScript tricks or you're a pro looking to refresh your memory, get ready to explore the magic of JavaScript string methods.
What are String methods in JavaScript?
String methods in JavaScript are built-in functions or operations that can be applied to strings (sequences of characters) to perform various operations and manipulations on them. These methods help us work with strings in different ways, such as modifying them, searching for specific substrings, extracting parts of a string, and more.
1. charAt(index):
Returns the character at the specified index in the string.
const str = "Hello, World!";
const charAtIdx = str.charAt(7);
console.log(charAtIdx); // Output: 'W'
2. charCodeAt(index):
This function retrieves the Unicode value of a character at a specified index in the string.
const str = "Hello, World!";
const codeIdx = str.charCodeAt(7);
console.log(codeIdx); // Output: 87 (Unicode value for 'W')
3. concat(string2, string3, ...):
Concatenates two or more strings and returns a new string.
const str1 = "Hello";
const str2 = ", ";
const str3 = "World!";
const result = str1.concat(str2, str3);
console.log(result); // Output: "Hello, World!"
4. indexOf():
Returns the index of the first occurrence of a substring or character in the string, starting from the given index(optional).
const str = "Hello, World!";
const indexOfComma = str.indexOf(",");
console.log(indexOfComma); // Output: 5
5. startsWith(substring):
This function checks whether a given string begins with a specific substring and returns a Boolean value.
const text = "Hello, World!";
const startsWithHello = text.startsWith("Hello");
console.log(startsWithHello); // Output: true
6. endsWith(substring):
This function checks if a string ends with a specific substring and returns a Boolean value.
const text = "Hello, World!";
const endsWithWorld = text.endsWith("World!");
console.log(endsWithWorld); // Output: true
7. includes(substring):
This function checks whether a string contains a specified substring and returns a Boolean value.
const text = "Namaste, JavaScript!";
const includesJS = text.includes("JavaScript!");
console.log(includesJS); // Output: true
8. substring(start, end):
A part of a string is obtained by selecting characters between specified start and end positions.
const text = "Hello, World!";
const substring = text.substring(0, 8);
console.log(substring); // Output: "Hello, W"
9. slice(startIndex, endIndex):
Extracts a portion of the string between the specified indices, similar to substring.
const text = "Welcome to JavaScript";
const sliced = text.slice(11, 21);
console.log(sliced); // Output: "JavaScript"
10. substr(startIndex, length):
Extracts a substring from the original string, starting at the specified index and extending for a specified length.
const text = "Hello, World!";
const substr = text.substr(7, 5);
console.log(substr); // Output: "World"
11. toLowerCase():
Converts the string to lowercase.
const str = "Namaste, JavaScript!";
const lowerCaseString = str.toLowerCase();
console.log(lowerCaseString); // Output: namaste, javascript!
12. toUpperCase():
Converts the string to uppercase.
const text = "Namaste, JavaScript!";
const uppercase = text.toUpperCase();
console.log(uppercase); // Output: "NAMASTE, JAVASCRIPT!"
13. trim():
Removes whitespace from the beginning and end of a string.
const text = " Hello, World! ";
const trimmedtxt = text.trim();
console.log(trimmedtxt); // Output: "Hello, World!"
14. split(separator, limit):
This function splits a string into an array of substrings using a specified separator.
const str = "apple,banana,orange";
const fruits = str.split(",");
const limitedSplit = str.split(",", 2);
console.log(fruits); // Output: ['apple', 'banana', 'orange']
console.log(limitedSplit); // Output: ['apple', 'banana']
15. replace(old, new):
Replaces occurrences of a substring with a new string.
const text = "Hello, World!";
const replaced = text.replace("World", "Universe");
console.log(replaced); // Output: "Hello, Universe!"
16. match(regexp):
Searches a string for a specified pattern (regular expression) and returns an array of matched substrings.
const text = "The quick brown fox jumps over the lazy dog";
const pattern = /[A-z]+/g; // Matches one or more "l" characters globally
const matches = text.match(pattern);
console.log(matches); // Output: ['The', 'quick', 'brown', 'fox', 'jumps', 'over', 'the', 'lazy', 'dog']
17. search(regexp):
Searches a string for a specified pattern (regular expression) and returns the index of the first match.
const text = "Hello, World!";
const pattern = /W/;
const index = text.search(pattern);
console.log(index); // Output: 7 (index of the first "W" character)
18. localeCompare(otherString):
Compares two strings based on the current locale and returns a value indicating their relative ordering.
const str1 = "apple";
const str2 = "banana";
const comparison = str1.localeCompare(str2);
console.log(comparison); // Output: -1 (a negative value (str1 comes before str2 in the locale))
Conclusion
We've found ways to work with text in our look at JavaScript string methods. These methods help us do simple or fancy things with words. Keep this cheat sheet handy to help with text tasks!
Thanks for being a part of this string journey! Stay curious, keep coding, and see you in our next blog post! ππ
Top comments (0)