How to Match an Exact String with JavaScript

image

Sometimes, we want to find an exact string within our JavaScript code.

In this article, we'll look at how to find an exact string with JavaScript.

Using the String.prototype.match Method

We can use the JavaScript string instance's match method to search for a string that matches the given pattern.

For instance, we can write:

const str1 = "abc";
const str2 = "abcd";
console.log(str1.match(/^abc$/));
console.log(str2.match(/^abc$/));

to call match with a regex that matches the exact word.

^ is the delimiter for the start of the word.

And $ is the delimiter for the end of the word.

Therefore, the regex matches the exact word in between the delimiters.

The first console log should log 'abc' as a match.

And the 2nd console log should log null .

We can convert the matched strings to an array.

For instance, we can write:

const str1 = "abc";
console.log([...str1.match(/^abc$/)]);

We use the spread operator to convert the match object to an array since the match object is an iterable object.

Conclusion

We can match an exact string with JavaScript by using the JavaScript string's match method with a regex pattern that has the delimiters for the start and end of the string with the exact word in between those.

Enjoyed this article?

Share it with your network to help others discover it

Continue Learning

Discover more articles on similar topics