How to find if an array contains a specific string in JavaScript/jQuery?

Can someone tell me how to detect if “specialword” appears in an array? Here’s an example of what I’m working with: categories: [ “specialword”, “word1”, “word2” ]

I’m just trying to figure out the best way to check if that specific string exists. Any help using javascript find string in array methods would be great!

I’ve been working with JavaScript for quite a while, and for modern codebases, this is my go-to method.

You can easily use .includes() for this! It’s super clean and works like a charm:

if (categories.includes("specialword")) {
  console.log("Found it!");
}

This method is supported in all modern browsers and keeps your code neat. For most javascript find string in array needs, this is the first thing I reach for.

Totally agree with Ian! That’s a great modern approach. But in case you’re dealing with legacy code or older browsers (which I’ve had to wrangle a few times)…

You might want to consider using jQuery’s $.inArray():

if ($.inArray("specialword", categories) !== -1) {
  console.log("Found the string!");
}

This was the standard before ES6 gave us .includes(). It still gets the job done effectively if you’re relying on jQuery elsewhere in your project. So yep, another solid tool for the javascript find string in array task.

Nice! I’ve been maintaining older codebases for years, so here’s another classic alternative I’ve had to use more than a few times.

If jQuery isn’t part of your stack but you still want something widely supported, indexOf() works really well:

if (categories.indexOf("specialword") > -1) {
  console.log("Yep, it's there!");
}

It’s reliable and has been around forever. Not quite as clean as .includes(), but when you’re deep in compatibility territory, it’s a safe bet. Definitely another option in your javascript find string in array toolbox.