JavaScript String Matching Methods
Tags: javascript, webdev, tutorial
Published: 2020-10-17 02:56:31


This tutorial will cover ways to find the match of a string within either another string or within an array, including:

- strict equality
- `includes()`
- `test()`
- `match()`

_This is not an exhaustive guide to all available methods, but ones quite useful in everyday scenarios_.

## Strict Equality

If you are comparing two strings with the expectation that they are either fully matched or not, then you can use a strict equality check.

```js
const stringA = 'Hello World';
const stringB = 'Hello World';

console.log(stringA === stringB);
// output: true
```

An example scenario is checking for a particular post type within post metadata as from a headless CMS or other API endpoint, to alter some part of the display:

```js
if(data.post.type === 'blog') {
  // display logic here
}
```

## `includes()`

The `includes()` method is available for both strings and arrays of strings.

**Important to note** that this type of match is case sensitive.

### String `includes()`

[Per MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/includes):

> The `includes()` method determines whether one string may be found _within_ another string, returning true or false as appropriate.

You can use this to find keywords or word fragments within a phrase:

```js
const phrase = 'She sells seashells by the seashore'.
const fragment = 'sea';

console.log(phrase.includes(fragment);
// output: true
```

### Array `includes()`

[Per MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/includes):

> The `includes()` method determines whether an array includes a certain value among its entries, returning `true` or `false` as appropriate.

If you've ever used strict equality to check if at least one in a series of values matches, then this is a nice upgrade to consider!

In other words, turn this:

```js
if(value === 'valueA' || value === 'valueB' || value === 'valueC')
```

Into this:

```js
if(['valueA', 'valueB', 'valueC'].includes(value))
```

## `test()`

[Per MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/test):

> The `test()` method executes a search for a match between a regular expression and a specified string. Returns true or false.

Compared to using `includes()`, this allows us to match in a case-insensitive way.

Here is how to include the `i` flag to allow for case-insensitivity:

```js
const str = 'This is a Test.';
const regex = RegExp('test', 'i');

console.log(regex.test(str));
// output: true
```

## `match()`

Similar to `test()` except `match()` will return an array of found matches, which is more useful when you are not looking for an exact text string match and also need the value.

In this example, we can use it to get the path portion of a known URL (you may need a more strict matching pattern for your scenario):

```js
const url = 'https://website.com/page/path/';
const regex = /https:\/\/website\.com\/(\S+?)\/?$/;

const urlMatches = url.match(regex);
// urlMatches[0] contains the full matched string
const pagePath = urlMatches[1];

console.log(pagePath);
// output: "page/path"
```

> Normally [I write about CSS](https://moderncss.dev), but my day job requires writing JavaScript too. Feel free to drop a comment on other methods you find useful when looking for strings!