This content originally appeared on DEV Community and was authored by Maria Belan-Crawford
I've been reviewing some useful string methods that are built into JavaScript, and thought I'd share my favorites. Since this article is geared more towards beginners, I'll quickly review some core concepts relating to strings. Skip to the next header if you just want to see some useful string methods!
What is a String, you ask?
In JavaScript, strings are any sequence of characters. When you use a string in JavaScript, it must be wrapped in single or double quotes, like this:
const greeting = 'Hello, how are you today?'
//or
const greeting2 = "Hey! What's up?"
Notice that in greeting2
, there is a single quote in "What's". This is ok, because we wrapped it in double quotes, and one single quote isn't going to give us issues! We would, however, have run into errors if we tried to wrap greeting2
in single quotes. For a situation like that, you can use the escape character, \
, to print the next character "as-is". Here's an example:
const sentence = 'Hey, how\'s it going?'
//or
const sentence2 = "It\'s a nice day, Let\'s go for a walk!"
You can check and see what type of data you're working with by using the typeof
prefix, like this:
const greeting = "Hello World"
console.log(typeof greeting) //this will print 'string' to the console!
Sometimes in JavaScript, you will run into numbers being represented as strings. If a number is represented as a string, you will be able to use String methods on them, but you will get some funny behavior if you try to use them as numbers. For instance:
const fakeNum = '123'
const actualNum = 456
console.log(fakeNum + actualNum) //prints 123456... which is a string!
This is because JavaScript is what's known as a 'weakly-typed' language. In the above example, when the program runs, JavaScript is deciding that actualNum
's data type is string. This happens because of the attempt to add it to fakeNum
, which is a string. So when you add them together, JavaScript will 'concatenate' them, or link them together in a chain. Here is another example of concatenation using +
, or the addition operator:
console.log('Hey there ' + 'stranger!')
Now that we've covered some string basics, we can cover...
Some Awesome String Methods
The full scoop on Strings in JS is available at the MDN Web Docs, but here are a few methods that I really enjoy:
1. String.prototype.concat()
Remember when we concatenated that string earlier? There is a function (or method, since it "lives" on the String object built into JavaScript) that can do that for us: concat()
! All we need to do is call that method on the string we want to concatenate (this is what the double parentheses ()
are for, and we access the method it by using dot notation - the .
in .concat()
), and pass in either one string, or a bunch of strings separated by commas.
Note: Every JavaScript String method is automatically available to anything that has a data type of string. It's magic!
No need for long chains of plus signs. Take a look:
const place = 'World'
console.log('Hello'.concat(" ", place))
//prints "Hello World"
Here we are "calling" concat
on the string "Hello". Notice that the strings are concatenated as-is, and we have to account for spaces.
We can also concatenate by "spreading" strings into concat
from an Array, using the ES6 spread operator ...
. You can think of ES6 as just an newer version of JavaScript. If you're interested, you can learn more about ES6 and JavaScript Language standards here. It sounds scary, but I promise, it's actually really simple to use. Here it is in action:
const greeting = ["Well ", "hello", " ", "there", "!"]
console.log("".concat(...greeting))
//prints "Well hello there!"
Because concat
can accept multiple strings, we can use the spread operator! Notice that we had to call concat
on an empty string. We needed that empty string because the concat
method comes with the String object, and we need a string to gain access to it it using dot notation, i.e. "".concat(string, string2)
On to the next method!
2. String.protoype.repeat()
Say you wanted to add 4 exclamation points to the end of a string. You could concatenate them, like this:
const greeting = "Hello, person"
//using +
console.log(greeting + "!" + "!" + "!" + "!")
//using the concat String method
console.log(greeting.concat("!", "!", "!", "!"))
//Both of these will print "Hello, person!!!!"
But that is tedious! What if we had 10 exclamation points?
Let's try the repeat
method, instead:
const greeting = "Hello, person"
console.log(greeting + "!".repeat(10))
console.log(greeting.concat("!".repeat(10)))
//Both of these will print "Hello, person!!!!!!!!!!"
Amazing! I love this one. repeat
accepts any positive number, 0 to +Infinity. Be careful when using it, since as of writing this post, it isn't supported by older versions Internet Explorer.
3. String.prototype.includes()
Another ES6 String method, includes
, will check if the calling string contains the string that is passed into it. You can also tell includes
when to start searching in the string by passing in an optional position. It returns a boolean (true or false).
Take a look at these examples:
const drinks = "We have Coffee, Tea, and Soda"
console.log(drinks.includes("Coffee")) // returns true
console.log(drinks.includes("Tea")) //returns true
console.log(drinks.includes("Cof")) //returns true
console.log(drinks.includes("Juice")) //returns false
console.log(drinks.includes("Coffee", 8)) //returns true
console.log(drinks.includes("Coffee", 9)) //returns false
In all of the above examples, drinks
is the calling string.
Notice that it doesn't matter if there are other characters or spaces right next to the matches. In the last two lines, we passed in a number representing the position to start searching the string. With 0 being the first position in the string (where the "W" is), we see that "Coffee" starts at position 8. If we try to search past that for "Coffee", we won't find it!
What about capitalization?
const drinks = "We have Coffee, Tea, and Soda"
console.log(drinks.includes("coffee")) // returns false!!
It turns out that the includes
method is case-sensitive... But there are ways to get around capitalization!
4. String.prototype.toLowerCase() and String.prototype.toUpperCase()
Both of these are very similar. They return the calling string, converted to all lowercase or all uppercase. Here's an example:
//calling toUpperCase against word
const word = "apples"
console.log(word.toUpperCase()) //returns "APPLES"
//calling toLowerCase against sentence
const sentence = "I Like Turtles."
console.log(word.toLowerCase()) //returns "i like turtles."
Notice that we simply need to call these methods against a string, and do not need to pass anything into them.
You might be thinking... "can we use these methods with includes
to get around the capitalization issue we were having earlier?"
The answer is yes!
Here's the same example from before, but using toLowerCase
:
const drinks = "We have Coffee, Tea, and Soda"
console.log(drinks.toLowerCase().includes("coffee")) // returns true!!
Excellent! It doesn't matter what case the original string is in. Since we called toLowerCase
on it, we know that includes
will be searching through a lowercase version of the original string. As long as we pass in a lowercase string for it to search with, it will work.
There's another way to handle capitalization in JavaScript, by using something called Regular Expressions. Regular Expressions are a little outside the scope of this post, and are a tough topic to grasp if you're new to them. If you're interested in learning more about them, check out this documentation on Regular Expressions.
Still, I'll end this post with an example using a regular expression so you can see how powerful these methods can be.
5. String.prototype.replace(), String.prototype.replaceAll()
The replace
String method accepts two things as arguments:
a pattern: either a string or a regular expression (see above)
a replacement: either another string, or a function that is run every time a match is made.
This is probably my favorite method in this list. Here is a super simple example of using replace
:
const fruits = "apple, orange, banana, orange, pineapple, guava"
console.log(fruits.replace("orange", "kiwi"))
// prints "apple, kiwi, banana, orange, pineapple, guava"
You can see that replace
looked for "orange" in the string, and replaced it with "kiwi"... But it only got the first one. We can use another method called replaceAll
to handle multiples, like this:
const fruits = "apple, orange, banana, orange, pineapple, guava"
console.log(fruits.replaceAll("orange", "kiwi"))
// prints "apple, kiwi, banana, kiwi, pineapple, guava"
Great! We can even pass in a function to do something with the string that is matched:
const fruits = "apple, orange, banana, orange, pineapple, guava"
console.log(fruits.replaceAll("orange", function(fruit){
return fruit.toUpperCase()
}))
// prints "apple, ORANGE, banana, ORANGE, pineapple, guava"
// In writing the function, we can use ES6's fat arrow
// syntax, and remove the return statement
// to clean this up a bit:
console.log(fruits.replaceAll("orange", fruit => fruit.toUpperCase() ))
// prints "apple, ORANGE, banana, ORANGE, pineapple, guava"
In the above example, the function takes in an argument fruit
. Here, fruit
represents whatever was matched by replaceAll
. The function is called every time there is a match, returning an uppercase version of what was matched by replaceAll
in the calling string, fruits
!
Now, you're not limited to replaceAll
to match multiples. You can actually use replace
with a regular expression to match multiples as well. I promised I'd end with a regular expression example, so here it is:
const sentence = "The punctuation! Let's flip it? Cool?"
// the long way
console.log(
sentence.replace(/[?!]/g, function (punct) {
if (punct === '?') {
return '!'
} else {
return '?'
}
})
)
//the ES6 way
console.log(
sentence.replace(/[?!]/g, punct => (punct === '?') ? "!" : "?")
)
// both of these console.logs will print
// "The punctuation? Let's flip it! Cool!"
In the above example, we called the replace
method against the string sentence
. We passed a regular expression /[?!]/g
and a function into that call. The regular expression will match any "?" and any "!" in the string because we included the g
or global
flag. You can see that the global flag is what makes replace
work more like replaceAll
. Awesome, right?
The function that we passed in takes a parameter punct
, which represents the punctuation that is currently being matched (remember, this function runs once for every match).
Note in the example that there are two versions of the same function, the "long way", and "the ES6 way".
First we used an if...else statement to return either "?" or "!" based on what the current match was. Note that the return value of this function ends up being the replacement!
In the ES6 version, we used a ternary operator, like this (condition) ? true : false
instead of the if statement. Because we only had one return value, we didn't need that return statement, either!
This is how we managed to swap all of the "!"s for "?"s.
Almost magic, isn't it?
Whew!
Conclusion
Thank you so much for sticking around to read this post. As a recap, these are the JS String methods that we covered:
- concat()
- repeat()
- includes()
- toLowerCase(), toUpperCase()
- replace(), replaceAll()
If you liked this post or have any feedback, please let me know! I would also love to know what you favorite JS String methods are.
There are a lot more that I didn't cover here.
If you want to read more about strings, JavaScript's String object, or other String methods, definitely check out the documentation at Mozilla.
Happy coding!
This content originally appeared on DEV Community and was authored by Maria Belan-Crawford
Maria Belan-Crawford | Sciencx (2021-04-23T23:35:13+00:00) My Favorite JS String Methods. Retrieved from https://www.scien.cx/2021/04/23/my-favorite-js-string-methods/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.