There are many ways to find specific characters, words or phrases within a string. Let’s look at the following declared text variable:
let text = "I like to drink cola but I don't always drink cola at home."
Now let’s look at how we can search for the word "cola" in this text. One option is to use the
indexOf(string, start) function.
Here, we would use the variable method of appending the function name to the declared variable:
The function includes an optional argument of a starting position, so the below will return 46, that is the second instance of this word, when doing the following:
In this case, this will work the same as
lastIndexOf("cola") which searches backwards from the end. Similarly, you can use the
text.search("cola"); // returns 16
While this function can’t start from a specified position, it can use regular expressions or patterns to aid with the search.
If you simply want to return true or false, you can append >-1 to the end of your expression or else use the
includes(string) function instead.
Note, when you have more than one instance of the search term, the above methods will only return the first instance.
An alternative is to use
match(string) and regular expressions to find every instance of the search term. This method returns an array:
text.match(/cola/g) // returns cola,cola
Here, we wrap the term in forward slashes and a g for greedy at the end. Greedy essentially means that it will find all occurrences. You can add a further
length property to count the instances:
text.match(/cola/g).length // returns 2
Replacing a search term is performed in similar fashion and does not require you to first use any find functions. The
replace(from, to) function can find and replace in a single call.
Using the same text variable example, on its own the
replace method will only replace the first instance of the search term:
However, we can again use regular expressions to fine tune the search:
Here, “cola” has been modified to be both greedy (g) and case-insensitive (i), so that it will replace all instances of “cola”, “Cola”, “COLA” or any combination in between with “Coca-Cola”.
A third use case for string manipulation is to extract specific parts of a string.
substr(start, length) and
split(character) are some of the common functions that are available.
Using the same declared text variable again, we can use
slice to select a part of the string by referencing the character indices:
text.slice(40,46); // returns "drink"
This also returns the same by starting from the end and working its way back:
Note, if we leave out the second argument, it will return the rest of the string.
We could also use the below where the second argument instead specifies the length of the string we want to extract:
You can also split a string into an array based on the space character, for example:
text.split(" "); // returns I,like,to,drink,cola,but,I,don't,always,drink,cola,at,home.
text.split(" "); // returns only the first item (index=0) "I"