Searching for Text in JavaScript using RegEx

by|inArticles||2 min read

Like in many other programming languages we can use regular expressions in JavaScript to search for a String value in a Text. In this article we will discuss how to use the match function.

Recently I had a simple use case for this at work. I wanted to shorten a given text only in the case when the text do not contain any spaces (usually this is the case when we have links which can not be "broken" into several parts). Hence, I needed to find the occurrences of spaces in one text. I remembered that the match function in JavaScript accepts regular expressions, like this:

let text = "This is some sample text to test our function";
console.log(text.match('some');
// Will create an array with the index of the word in the text where it was matched
// [ index: 4, ...]

If we are searching for just one word, this is fine. But if we are searching for more than one occurrences? Maybe we can use the matchAll function? Let's say we want to search for all the spaces in the text:

console.log(text.matchAll(' '));
// Will result in a RegExpStringIterator object

The matchAll function works as expected, but will give us an iterator. While this is correct, working with an iterator is a bit cumbersome. We need to use a for construct, track the occurrences ourselves and count.
There must be a simpler way, right?

As you maybe already guessed, the solution is the usage of the match function with a regular expression.  If we look at our suggester input parameters in the chrome developer console, we will see the following:

JavaScript match with regular expressions
JavaScript match with regular expressions

The interesting part is that we can use regular expressions directly (not wrapped in a string):

console.log(text.match(/some/));
// This will produce the same result as text.match('some');

To collect all occurrences in a text (all match groups) we just need to add the according command to the regular expression:

console.log(text.match(/some/g);
// Will produce an array ['some']

By the length of the array we can tell how many times our search string appeared in the given text. For my use case it means the following:

let matchedSpaces = text.match(/ /g);
// Will produce an array of spaces [' ', ' ', ' ', ...] 8 in total

console.log(matchedSpaces.lenght);
// Will output 8

Thank you for reading this far! Let’s connect. You can @ me on X (@debilofant) with comments, or feel free to follow. Please like/share this article so that it reaches others as well.

Related Articles

© Copyright 2024 - ersocon.net - All rights reservedVer. 415