Strings in JavaScript are not just sequences of characters; they come with a powerful set of built-in methods that allow you to manipulate and inspect them in various useful ways. From searching and concatenating to altering the case of characters, these methods make working with strings much more efficient.
charAt()
The charAt()
method returns the character at a specified index (position) in a string.
let text = "Hello, World!";
console.log(text.charAt(7)); // "W"
charCodeAt()
charCodeAt()
returns the Unicode of the character at a specified index.
console.log(text.charCodeAt(7)); // 87
concat()
The concat()
method concatenates (joins) two or more strings into one.
let greeting = "Hello";
let target = "World";
console.log(greeting.concat(", ", target, "!")); // "Hello, World!"
includes()
includes()
checks if a string contains a specified value, returning true or false as appropriate.
console.log(text.includes("World")); // true
indexOf()
The indexOf()
method returns the index of the first occurrence of a specified value in a string. If the value is not found, it returns -1.
console.log(text.indexOf("World")); // 7
slice()
slice()
extracts a part of a string and returns it as a new string, without modifying the original string.
console.log(text.slice(7, 12)); // "World"
split()
The split()
method divides a string into an ordered list of substrings by separating it at each occurrence of a specified separator string and returns them as an array.
console.log("2023-02-08".split("-")); // ["2023", "02", "08"]
substr()
substr()
returns a portion of the string, starting at the specified index and extending for a given number of characters afterwards.
console.log(text.substr(7, 5)); // "World"
toLowerCase() and toUpperCase()
These methods return the calling string value converted to lowercase or uppercase, respectively.
let mixedCase = "JaVaScRiPt";
console.log(mixedCase.toLowerCase()); // "javascript"
console.log(mixedCase.toUpperCase()); // "JAVASCRIPT"
Conclusion
JavaScript provides a rich set of methods for string manipulation, making tasks like searching within strings, modifying their content, and analyzing them much simpler. By mastering these methods, you can handle most string-related tasks efficiently and effectively, enhancing both the functionality and readability of your JavaScript code.