This post will discuss how to search a string for a specific character in JavaScript.

There are several ways to check a string for a specific character in JavaScript. Some of the common functions are:

1. Using includes() function

The includes() function is a modern and simple way of checking for a character or a substring in a string. This function returns true if the string contains the character, and false if it doesn’t. It is case-sensitive and accepts an optional second argument for the starting index. For example, to check if the string "Hello World" contains the character "r", we can use:

Download  Run Code

2. Using indexOf() function

The indexOf() function is a widely supported and versatile way of checking for a character or a substring in a string. This function returns the index of the first occurrence of the character in the string, or -1 if it is not found. It is also case-sensitive and accepts an optional second argument for the starting index. For example, using the same string and character as before, we can use:

Download  Run Code

 
If we only want to check for the existence of the character, we can compare the result with the return value of the indexOf() function (str.indexOf(char) !== -1 or str.indexOf(char) >= 0). Here’s an example:

Download  Run Code

3. Using match() or test() function

The match() function with a regular expression is a powerful and flexible way of checking for a characters or patterns in a string. This function returns an array of matches if the string matches the regular expression, or null if it does not. If we only want to check for the existence of the character, we can convert the result to a boolean value. For example, using the inputs as before, we can use:

Download  Run Code

 
Alternatively, we can use the test() function to match a string against a regular expression and return a boolean value accordingly. It can also be used to check for specific patterns or characters in the string. Here’s an example:

Download  Run Code

That’s all about searching a string for a specific character in JavaScript.