JavaScript offers a range of methods to work with and manipulate strings. These methods make our tasks easier and our code cleaner and more robust. Let's take a look at some of these methods that I frequently use, and probably, you'll also use them in building production applications.
The ‘toLowerCase’ method
The toLowerCase
method transforms a string to lowercase and returns the updated value. This method is useful when you need to compare two strings, as it standardizes their case.
const addon = 'bacon - $1';
const input = 'Bacon - $1';
console.log(addon === input); // false
console.log(addon.toLowerCase() === input.toLowerCase()); // true
The ‘split’ method
The split
method divides a string into an array. This method is especially useful when you need to access a certain portion of a string.
const addon = 'bacon - $1';
const elements = addon.split('-');
console.log(elements); // [ 'bacon ', ' $1' ]
const ingredient = elements[0];
console.log(ingredient); // bacon
In the above example, we've used the split
method that takes an argument '-' to divide the addon
string and returns an array for us to access a particular element in it.
The ‘replace’ method
Another useful string method that I often use is replace
. As the name suggests, this method replaces a portion of a string and returns the updated value.
const addon = 'bacon - $1';
const updated = addon.replace('$', '£');
console.log(updated); // bacon - £1
In the above code, we've replaced '$' with '£' using the replace
method.
As you can see, the replace
method takes two arguments: the first argument specifies what should be replaced, and the second argument defines the replacement.
Good to know that the replace
method replaces only the first occurrence. Use the replaceAll
method if you need to replace all the occurrences.
The ‘includes’ method
The includes
method takes an argument and returns a boolean indicating whether the argument exists within the string. This is yet another handy string method to check if a string contains a particular substring.
const addon = 'bacon - $1';
const isUSD = addon.includes('$');
console.log(isUSD); // true
The ‘trim’ method
The trim
method is useful for removing leading and trailing white spaces in a string. I mostly use this method to format user-provided strings.
const addon = ' bacon - $1 ';
const trimmed = addon.trim();
console.log(trimmed); // bacon - $1
As you can see in the above example, the trim
method effectively removes the extra spaces at the start and end of the addon
string and returns the updated value.
These are the string methods I frequently use when developing production applications. I hope you now have a clear understanding of how, why, and where to apply these methods, and can confidently utilize them in your upcoming project.
I have an article on JavaScript array methods I often use in building production apps, which you might find interesting. Feel free to take a look. Happy learning!