Javascript if word is in string

$a = 'how are you';
if (strpos($a,'are') !== false) {
    echo 'true';
}

In PHP, we can use the code above to check if a string contain specific words, but how can I do the same function in JavaScript/jQuery?

j08691's user avatar

j08691

203k31 gold badges259 silver badges271 bronze badges

asked Mar 22, 2011 at 8:18

Charles Yeung's user avatar

Charles YeungCharles Yeung

38.1k30 gold badges90 silver badges130 bronze badges

4

you can use indexOf for this

var a = 'how are you';
if (a.indexOf('are') > -1) {
  return true;
} else {
  return false;
}

Edit: This is an old answer that keeps getting up votes every once in a while so I thought I should clarify that in the above code, the if clause is not required at all because the expression itself is a boolean. Here is a better version of it which you should use,

var a = 'how are you';
return a.indexOf('are') > -1;

Update in ECMAScript2016:

var a = 'how are you';
return a.includes('are');  //true

Santhoshkumar's user avatar

answered Mar 22, 2011 at 8:22

naiquevin's user avatar

3

indexOf/includes should not be used for finding whole words:

A word (in western culture) is a drawing of a symbols close to each other, with some space between each word. A word is considered as such if it’s a complete piece of characters draw together and not a partial part of it:

"has a word".indexOf('wor')  // 6 ("wor" is not a word in this sentence)
"has a word".includes('ha') // true ("ha" is not a word in this sentence)

Check if a single word (whole word) is in the string

Find a real whole word, not just if the letters of that word are somewhere in the string.

const wordInString = (s, word) => new RegExp('\b' + word + '\b', 'i').test(s);

// tests
[
  '',            // true
  ' ',           // true
  'did',         // true
  'id',          // flase
  'yo ',         // flase
  'you',         // true
  'you not'      // true
].forEach(q => console.log(
  wordInString('dID You, or did you NOt, gEt WHy?', q) 
))

console.log(
  wordInString('did you, or did you not, get why?', 'you') // true
)

Check if all words are in the string

var stringHasAll = (s, query) => 
  // convert the query to array of "words" & checks EVERY item is contained in the string
  query.split(' ').every(q => new RegExp('\b' + q + '\b', 'i').test(s)); 


// tests
[
  '',            // true
  ' ',           // true
  'aa',          // true
  'aa ',         // true
  ' aa',         // true
  'd b',         // false
  'aaa',         // false
  'a b',         // false
  'a a a a a ',  // false
].forEach(q => console.log(
  stringHasAll('aA bB cC dD', q) 
))

answered Jan 12, 2014 at 23:41

vsync's user avatar

vsyncvsync

115k56 gold badges298 silver badges391 bronze badges

6

If you are looking for exact words and don’t want it to match things like «nightmare» (which is probably what you need), you can use a regex:

/bareb/gi

b = word boundary
g = global
i = case insensitive (if needed)

If you just want to find the characters «are», then use indexOf.

If you want to match arbitrary words, you have to programatically construct a RegExp (regular expression) object itself based on the word string and use test.

answered Mar 22, 2011 at 8:27

Stephen Chung's user avatar

Stephen ChungStephen Chung

14.5k1 gold badge35 silver badges48 bronze badges

You’re looking for the indexOf function:

if (str.indexOf("are") >= 0){//Do stuff}

answered Mar 22, 2011 at 8:22

evbailey's user avatar

evbaileyevbailey

3713 silver badges11 bronze badges

You might wanna use include method in JS.

var sentence = "This is my line";
console.log(sentence.includes("my"));
//returns true if substring is present.

PS: includes is case sensitive.

answered Apr 16, 2018 at 7:26

Neelansh Verma's user avatar

In javascript the includes() method can be used to determines whether a string contains particular word (or characters at specified position). Its case sensitive.

var str = "Hello there."; 

var check1 = str.includes("there"); //true
var check2 = str.includes("There"); //false, the method is case sensitive
var check3 = str.includes("her");   //true
var check4 = str.includes("o",4);   //true, o is at position 4 (start at 0)
var check5 = str.includes("o",6);   //false o is not at position 6

answered Oct 20, 2019 at 8:09

Zeni's user avatar

ZeniZeni

9071 gold badge11 silver badges24 bronze badges

1

An easy way to do it to use Regex match() method :-

For Example

var str ="Hi, Its stacks over flow and stackoverflow Rocks."

// It will check word from beginning to the end of the string

if(str.match(/(^|W)stack($|W)/)) {

        alert('Word Match');
}else {

        alert('Word not found');
}

Check the fiddle

NOTE: For adding case sensitiveness update the regex with /(^|W)stack($|W)/i

Thanks

Vineeth Sai's user avatar

Vineeth Sai

3,3897 gold badges22 silver badges34 bronze badges

answered Sep 20, 2018 at 6:33

Akshay kumar's user avatar

This will

/bwordb/.test("Thisword is not valid");

return false, when this one

/bwordb/.test("This word is valid");

will return true.

answered Jun 19, 2015 at 17:07

Jahid's user avatar

JahidJahid

21.1k9 gold badges89 silver badges107 bronze badges

var str1 = "STACKOVERFLOW";
var str2 = "OVER";
if(str1.indexOf(str2) != -1){
    console.log(str2 + " found");
}

answered Aug 29, 2018 at 6:09

pgksunilkumar's user avatar

Using a conditional ternary operator

str = 'I am on StackOverflow';
str.match(/(^|W)StackOverflow($|W)/) ? 'Found. Why lie?' : 'Not Found';

answered Jan 21, 2022 at 20:28

WiiLF's user avatar

WiiLFWiiLF

3043 silver badges11 bronze badges

If you’d like to find a single word in a string without regular expressions, you can do as follows:

function isWordInString(needle, haystack) {
  return haystack
    .split(' ')
    .some(p => (p === needle));
}
isWordInString('hello', 'hello great world!'); // true
isWordInString('eat', 'hello great world!'); // false

Advantages over regex:

  • Works with non-latin characters like Hebrew
  • No need to sanitize the word you search in the string. Some methods in other answers will fail and return a false positive when searching for a «.» (dot)

answered Jun 8, 2022 at 9:42

Arik's user avatar

ArikArik

5,0781 gold badge26 silver badges25 bronze badges

How to Check if a String Contains a Substring in JavaScript

When you’re working with a JavaScript program, you might need to check whether a string contains a substring. A substring is a string inside another string.

Specifically, you might need to check whether a word contains a specific character or a specific set of characters.

Thankfully, there are a few quick ways to achieve this with JavaScript.

In this article, you will learn two different ways you can check if a string contains a substring using JavaScript methods.

Specifically, you will learn:

  • How to use the built-in includes() JavaScript method.
  • How to use the built-in indexOf() JavaScript method.

Here is what we will cover in more detail:

  1. Syntax breakdown of the includes() method in JavaScript
    1. How to check if a string contains a specific substring using the includes() method
  2. Syntax breakdown of the indexOf() method in JavaScript
    1. How to check if a string contains a specific substring using the indexOf() method
  3. How to make a case-insensitive check with the includes() and indexOf() methods

What Is The includes() Method in JavaScript? includes() Method Syntax Breakdown

The JavaScript includes() method was introduced with ES6, and it is the most common and modern way of checking if a string contains a specific character or a series of characters.

The general syntax for the includes() method looks something similar to this:

string.includes(substring, index);

Let’s break it down:

  • string is the word you want to search through.
  • includes() is the method you call on the word you want to search through, which in this case is string.
  • The includes() method accepts two arguments — one is required, and one is optional.
  • The first argument the includes() method accepts is substring, and it is required. substring is the character or the series of characters you are checking to see if they exist within string.
  • The second argument the includes() method accepts is index, and it is optional. index refers to the position from which the search for substring will start — the default value is 0 because indexing in programming languages begins at 0.

The return value is a Boolean value. A Boolean value can either be true or false depending on whether the substring is present or not within the string.

Something to keep in mind is that the includes() method is case-sensitive.

How To Check if A String Contains A Specific Substring in JavaScript Using The includes() Method

Let’s see an example of how the includes() method works.

First, I created a variable that holds the string Hello, World — this is the string I want to search through:

let string= "Hello, World";

Next, I created a variable with the substring Hello — this is the substring I want to search for in the original string:

let string= "Hello, World";
let substring = "Hello";

Next, I will check if substring is present within string using the includes() method and print the result to the console:

let string= "Hello, World";
let substring = "Hello";

console.log(string.includes(substring));

// output
// true

The return value was true, meaning Hello is present in the variable string.

As mentioned in the section above, the includes() method is case-sensitive.

See what happens when I change the value of substring from Hello to hello:

let string= "Hello, World";
let substring = "hello";

console.log(string.includes(substring));

// output
// false

The return value, in this case, is false, as there is no substring hello with a lowercase h. So, keep this in mind when working with the includes() method — it differentiates between capital and lowercase letters.

Now, let’s see how to use the includes() method with the second argument, index.

As a reminder, the second argument specifies the position from which you want to start the search for the substring.

Let’s take the same string variable from the previous examples:

let string= "Hello, World";

I will change the value of the substring variable to H:

let string= "Hello, World";
let substring = "H";

And I will specify the search of the substring to start from position 0:

let string= "Hello, World";
let substring = "H";

console.log(string.includes(substring,0));

// output
// true

The return value is true because the substring H is at index position 0 within the string Hello, World.

Remember, the first letter in a string has a position of 0, the second a position of 1, and so on.

What Is The indexOf() Method in JavaScript? indexOf() Method Syntax Breakdown

Similar to the includes() method, the JavaScript indexOf() method checks if a string includes a substring.

The general syntax for the indexOf() method looks something similar to this:

string.indexOf(substring, index);

Let’s break it down:

  • string is the word you want to search through.
  • index0f() is the method you call on the word you want to search through, in this case, string.
  • The includes() method takes two arguments — one is required, and one is optional.
  • The first argument to the indexOf() method is substring, and it is required. substring is the character or the series of characters you are searching for.
  • The second argument to the indexOf() method is index, and it is optional. index refers to the position from which the search for substring will start. The default value is 0 because indexing in programming languages begins at 0.

The difference between the two methods is their return value.

The includes() method returns a Boolean value (a value that is either true or false), whereas the indexOf() method returns a number.

The number will be the starting index position where the substring you are looking for is found within the string. The return value will be -1 if the substring is not found in the string.

And just like the includes() method, the indexOf() method is case-sensitive.

How To Check if A String Contains A Specific Substring in JavaScript Using The indexOf() Method

Let’s use the same example from earlier to see how the indexOf() method works.

let string= "Hello, World";
let substring = "H";

There is the variable string with the original string, and the variable substring with the substring you are searching for.

let string= "Hello, World";
let substring = "H";

console.log(string.indexOf(substring));

// output
// 0

The output is 0, which is the starting position of the substring you are searching for.

In this case, the value you were searching for was a single character.

Let’s change the value of substring from H to Hello:

let string= "Hello, World";
let substring = "Hello";

console.log(string.indexOf(substring));

// output
// 0

The return value is again 0 since index0f() returns the starting position of the substring you are looking for. Since the first character of the substring is located at the 0 position, indexOf() returns 0.

Now, let’s change the value of substring from Hello to hello with a lowercase h:

let string= "Hello, World";
let substring = "hello";

console.log(string.indexOf(substring));

// output
// -1

The return value is -1. As mentioned earlier, index0f() is case-sensitive, so it cannot find a substring hello with lowercase h. And when indexOf() cannot find the given substring, it returns -1.

Finally, you can specify the index value you want to start your search from by passing the second argument that indexOf() accepts.

let string= "Hello, World";
let substring = "hello";

console.log(string.indexOf(substring,1));

// output
// -1

Say you want to start your search from position 1. The return value is -1 since the starting position of the substring you are searching for is 0. An exact match is not found at position 1 so indexOf() returns -1.

How To Make A Case-Insensitive Check With the includes() and indexOf() Methods

So far, you have seen that the includes() and indexOf() methods are case-insensitive.

But what happens when you want to perform a case-insensitive check?

To do a case-insensitive check and see if a substring is present within a string, you will need to convert both the original string and the substring to lowercase using the toLowerCase() JavaScript method before calling one of the two methods.

Here is how you would do that using the includes() method:

let string= "Hello, World";
let substring = "hello";

console.log(string.toLowerCase().includes(substring.toLowerCase()));

// output
// true

By default, the return value would have been false because the original string contains an uppercase H, whereas the substring contains a lowercase h. After converting both strings to lowercase, you don’t have to worry about the capitalization of the original string and the substring you are searching for.

And here is how you would do the same thing using the indexOf() method:

let string= "Hello, World";
let substring = "hello";

console.log(string.toLowerCase().indexOf(substring.toLowerCase()));

// output
// 0

By default, the return value would have been -1 because the original
string and the substring you are searching for have different cases.

After using the toLowerCase() method, the indexOf() method returns the staring position of the substring.

Conclusion

And there you have it! You now know how to check if a string contains a substring in JavaScript.

To learn more about JavaScript, head to freeCodeCamp’s JavaScript Algorithms and Data Structures Certification.

It’s a free, well-thought-out, and structured curriculum where you will learn interactively. In the end, you will also build 5 projects to claim your certification and solidify your knowledge.

Thanks for reading!



Learn to code for free. freeCodeCamp’s open source curriculum has helped more than 40,000 people get jobs as developers. Get started

Метод includes() проверяет, содержит ли строка заданную подстроку, и возвращает, соответственно true или false.

Синтаксис

str.includes(searchString[, position])

Параметры

searchString

Строка для поиска в данной строке.

position Необязательный

Позиция в строке, с которой начинать поиск строки searchString, по умолчанию 0.

Возвращаемое значение

true, если искомая строка была найдена в данной строке; иначе false.

Описание

Этот метод позволяет вам определять, содержит ли строка другую строку.

Чувствительность к регистру символов

Метод includes() является регистрозависимым. Например, следующее выражение вернёт false:

'Синий кит'.includes('синий'); // вернёт false

Примеры

Использование includes()

var str = 'Быть или не быть вот в чём вопрос.';

console.log(str.includes('Быть'));       // true
console.log(str.includes('вопрос'));    // true
console.log(str.includes('несуществующий')); // false
console.log(str.includes('Быть', 1));    // false
console.log(str.includes('БЫТЬ'));       // false

Полифил

Этот метод был добавлен в спецификации ECMAScript 2015 и может быть недоступен в некоторых реализациях JavaScript. Однако, можно легко эмулировать этот метод:

if (!String.prototype.includes) {
  String.prototype.includes = function(search, start) {
    'use strict';
    if (typeof start !== 'number') {
      start = 0;
    }

    if (start + search.length > this.length) {
      return false;
    } else {
      return this.indexOf(search, start) !== -1;
    }
  };
}

Спецификации

Specification
ECMAScript Language Specification
# sec-string.prototype.includes

Поддержка браузерами

BCD tables only load in the browser

String.prototype.contains

В Firefox с версии 18 по версию 39, этот метод назывался «contains». Он был переименован в «includes» в замечании баг 1102219 по следующей причине:

Как было сообщено, некоторые сайты, использующие MooTools 1.2, ломаются в Firefox 17. Эта версия MooTools проверяет существование метода String.prototype.contains() и, если он не существует, добавляет свой собственный. С введением этого метода в Firefox 17, поведение этой проверки изменилось таким образом, что реализация String.prototype.contains(), основанная на MooTools, сломалась. В результате это изменение было отключено в Firefox 17. Метод String.prototype.contains() доступен в следующей версии Firefox — Firefox 18.

MooTools 1.3 принудительно использует свою собственную версию метода String.prototype.contains(), так что использующие его веб-сайты не должны ломаться. Тем не менее, следует отметить, что сигнатура метода в MooTools 1.3 отличается от сигнатуры метода в ECMAScript 2015 (во втором аргументе). В MooTools 1.5+ сигнатура изменена для соответствия стандарту ES2015.

В Firefox 48, метод String.prototype.contains() был удалён. Следует использовать только String.prototype.includes().

Смотрите также

Last Updated — May 20, 2022

Let’s say you have a string and you want to check if it contains a specific word, character or substring. In this article, you will learn about different ways in which you can perform the check using JavaScript. Here are a few variables that we are going to use:

JavaScript

var theString = "I have been looking for Sam.";
var theWord  = "look";
var theCharacter = "I";
var theSubstring = "for Sam";

On This Page

  1. Using String.indexOf() to Check if String Contains Substring
  2. Using String.includes() to Check if String Contains Substring
  3. Using String.search() to Check if String Contains Substring
  4. Using String.match() to Check if String Contains Substring
  5. Quick Summary

Using String.indexOf() to Check if String Contains Substring

The fastest way to check if a string contains a particular word or substring is with the help of String.indexOf() method. This method returns the index of the first occurrence of the specified substring inside the calling String object. If the substring or word is not found, it returns -1.

This means that you can compare the value returned by the indexOf() method to see if it is equal to -1. If the value is not -1, the calling string contains the substring we are looking for.

JavaScript

var theString = "I have been looking for Sam.";
var theWord  = "looking";
var theCharacter = "I";
var theSubstring = "for Sam";


// Output — The word "looking" exists in given string.
if (theString.indexOf(theWord) !== -1) {
  console.log('The word "' + theWord + '" exists in given string.');
}

// Output — The character "I" exists in given string.
if (theString.indexOf(theCharacter) !== -1) {
  console.log('The character "' + theCharacter + '" exists in given string.');
}

// Output — The substring "for Sam" exists in given string.
if (theString.indexOf(theSubstring) !== -1) {
  console.log('The substring "' + theSubstring + '" exists in given string.');
}

You are not limited to the strict inequality operator (!==), you can also use > -1. This is because if the word or substring exists in the given string, the index returned would always be greater than or equal to 0. However, remember that the greater than operator (>) is slower than the strict inequality operator (!==).

One important point that should be kept in mind is that if you meant to search exactly for “look” in the above string, the method would still return an index greater than -1 because “looking” exists in the string. If you are looking for exact matches, you will have to be extra careful.

This method is case-sensitive so you would have got -1 if you searched for “Looking” instead of “looking”.

Using String.includes() to Check if String Contains Substring

You can also use the String.includes() to check if a string contains another word, character or substring. This method will return TRUE if the substring can be found within the main string and FALSE otherwise.

JavaScript

var theString = "I have been looking for Sam.";
var theWord  = "looking";
var theCharacter = "I";
var theSubstring = "for Sam";

// Output — The word "looking" exists in given string.
if (theString.includes(theWord)) {
  console.log('The word "' + theWord + '" exists in given string.');
}

// Output — The character "I" exists in given string.
if (theString.includes(theCharacter)) {
  console.log('The character "' + theCharacter + '" exists in given string.');
}

// Output — The substring "for Sam" exists in given string.
if (theString.includes(theSubstring)) {
  console.log('The substring "' + theSubstring + '" exists in given string.');
}

Just like String.indexOf(), this method is also case-sensitive. One major issue with this method is that the browser support for String.includes() is not as good as String.indexOf(). If you don’t care about the browser support for Internet Explorer, you can use String.includes() without second thought.

Using String.search() to Check if String Contains Substring

String.search() is another method that you can use to check if a string contains another word, substring or character inside the main string. Unlike String.indexOf() and String.include() that we have covered so far, String.search() accepts a regular expression as its parameter. This means that you can also use it to search for complex patterns instead of basic strings.

String.search() returns the index of first match between the regular expression and given string. If no match is found it returns -1. You can compare the return value of String.search() with -1 to see if the given string has the substring you are looking for.

JavaScript

var theString = "I have been looking for Sam.";
var theWord = "looking";
var theCharacter = "I";
var theSubstring = "for Sam";
var theWordExp  = /looking/g;
var theCharacterExp = /I/g;
var theSubstringExp = /for Sam/g;

// Output — The word "looking" exists in given string.
if (theString.search(theWordExp) !== -1) {
  console.log('The word "' + theWord + '" exists in given string.');
}

// Output — The character "I" exists in given string.
if (theString.search(theCharacterExp) !== -1) {
  console.log('The character "' + theCharacter + '" exists in given string.');
}

// Output — The substring "for Sam" exists in given string.
if (theString.search(theSubstringExp) !== -1) {
  console.log('The substring "' + theSubstring + '" exists in given string.');
}

If you are only looking for basic strings, I would suggest that you use either String.includes() or String.indexOf() instead of String.seach().

Using String.match() to Check if String Contains Substring

The String.match() method is used to retrieve all the matches of a regular expression inside the main string. You can use it to check the existence of another word, character or substring inside the main string by passing them as regular expressions. This method will return null if no matches are found.

JavaScript

var theString = "I have been looking for Sam.";
var theWord = "looking";
var theCharacter = "I";
var theSubstring = "for Sam";
var theWordExp  = /looking/g;
var theCharacterExp = /I/g;
var theSubstringExp = /for Sam/g;

// Output — The word "looking" exists in given string.
if (theString.match(theWordExp) !== null) {
  console.log('The word "' + theWord + '" exists in given string.');
}

// Output — The character "I" exists in given string.
if (theString.match(theCharacterExp) !== null) {
  console.log('The character "' + theCharacter + '" exists in given string.');
}

// Output — The substring "for Sam" exists in given string.
if (theString.match(theSubstringExp) !== null) {
  console.log('The substring "' + theSubstring + '" exists in given string.');
}

Actually, you can use String.match() to get a lot more information than just check the existence of a substring. If you include the g flag in the regular expression, it returns the whole array of matched substrings in case of a match. Using it to check if a string has another substring might be overkill. Also, this method is slow compared to other substring checking methods.

Quick Summary

Let’s recap everything that we have covered in this tutorial.

  1. You can use four different methods to check if a string contains another word or substring. These methods are: indexOf(), includes(), search() and match().
  2. The indexOf() method will return the index of the matched string while includes() just returns a Boolean TRUE or FALSE. You can use them both without worrying too much about performance. Both these methods are case-sensitive.
  3. If you are planning to perform case-insensitive searches, using search() with the case-insensitive flag i might be a better idea. However, you will have to escape some special characters for the search to be successful. Using the search() method also gives you more flexibility over simple string matching methods indexOf() and includes().
  4. You can also use match() to see if a string has another word or substring. However, if you just want to know if a match exists, using it might be an overkill.

Let me know if there is anything that you would like me to clarify. Also, you are more than welcome to comment if you know other techniques to check if a string contains another word, character or substring in JavaScript.

Rate this post —

Loading…

You can check if a JavaScript string contains a character or phrase using the includes() method, indexOf(), or a regular expression. includes() is the most common method for checking if a string contains a letter or series of letters, and was designed specifically for that purpose.


Checking if a string contains a substring is a common task in any programming language. For instance, say you are building an online game. You may want to check whether a username contains a banned phrase to make sure all usernames are suitable for your game.

Get offers and scholarships from top coding schools illustration

Find Your Bootcamp Match

  • Career Karma matches you with top tech bootcamps
  • Access exclusive scholarships and prep courses

Select your interest

First name

Last name

Email

Phone number

By continuing you agree to our Terms of Service and Privacy Policy, and you consent to receive offers and opportunities from Career Karma by telephone, text message, and email.

JavaScript String Contains

There are three methods for checking if a JavaScript string contains another character or sequence of characters:

  • includes().
  • indexOf().
  • Regular expressions (regex).

In this tutorial, we’re going to discuss methods you can use to check if a JavaScript string contains another string using these three approaches.

String Contains JavaScript: includes()

The JavaScript includes() method, introduced in ES6, determines whether a string contains the characters you have passed into the method. If the string contains certain characters, the method will return “true.”

If the specified string does not contain the characters for which you are looking, includes() will return “false.”

The syntax for the includes() method is:

The value “string” refers to the characters through which we will search. “word” refers to the characters for which we are looking.

Here’s an example of the includes() method in action:

let example = "Example String!";
let ourSubstring = "Example";

if (example.includes(ourSubstring)) {
	console.log("The word Example is in the string.");
} else {
	console.log("The word Example is not in the string.");
}

Our code returns: The word Example is in the string.

On the first two lines, we declare two JavaScript variables. The first variable is the string through which we want to search. The second is the substring that we want to find in our original string. In other words, we’ll search for whether the first variable contains the contents of the second variable.

Next, we use an if statement to evaluate whether the “example” variable contains the contents of the “ourSubstring” variable.

If “example” contains the word “Example”, our statement evaluates to true. This means that the console.log() statement in the body of our “if” statement is run. Otherwise, our “else” statement is run.

includes() is case-sensitive, so if we changed the case of our substring, “false” would be returned.

includes() Second Argument

The includes() method lets you specify a second argument. This second argument is the index number at which includes() should start searching for your substring. The first character would have an index of “0”, the second “1”, and so on. This is because lists are indexed from zero.

Let’s check whether the word “Example” appears after the index position 7 in our string:

let example = "Example String!";
let ourSubstring = "Example";

if (str.includes(ourSubstring, 7)) {
	console.log("The word Example is in the string.");
} else {
	console.log("The word Example is not in the string");
}

The includes() method returns the index position at which our string begins. Our code returns “The word Example is not in the string.” While our string does include the word “Example,” the word appears before the index value “7,” which is the space between “Example” and “String!”

JavaScript Check if String Contains: indexOf()

The JavaScript indexOf() method, like includes(), checks if a string includes another string. What is different is the output from these two functions.

When we use the includes() method, the method returns a boolean: true or false. indexOf() returns the starting index location of the substring. Or, if the string does not include the substring, we’ll get “-1.”

Let’s look at the syntax for this method:

Like in our includes() example, “string” refers to the value through which we are searching. “word” is the phrase or character for which we are searching.

Here’s an example of indexOf() in JavaScript:

let example = "Example String!";
let ourSubstring = "Example";

if (example.indexOf(ourSubstring) != 0) {
	console.log("The word Example is in the string.");
} else {
	console.log("The word Example is not in the string.");
}

Our code returns: The word Example is in the string. We have used an “if” statement like we did in our last example. This statement displays a particular message to the console depending on if our string contains a substring.

We check if the indexOf() method does not return -1. If it does, the “else” statement is run. -1 denotes that our string could not be found. Otherwise, the code within our “if” statement is executed.

Let’s use indexOf() on a string that doesn’t contain a substring:

let str = "Example String!";
let ourSubstring = "Bananas";

str.indexOf(ourSubstring);

Our code returns -1 because our substring cannot be found.

indexOf(), like the includes() method, is case-sensitive. If we want our search to start at a certain index value, we can use another argument:

Venus profile photo

«Career Karma entered my life when I needed it most and quickly helped me match with a bootcamp. Two months after graduating, I found my dream job that aligned with my values and goals in life!»

Venus, Software Engineer at Rockbot

let str = "Example String!";
let ourSubstring = "Example";

str.indexOf(ourSubstring, 7);

Because an exact match is not found starting at the index value seven, our code returns -1.

String Contains JavaScript: Regex

We can also make use of JavaScript regular expressions—or regex—to check if a string contains a substring. Regex can be incredibly useful due to its flexibility: you have a lot of control over what you search for, and where.

We can use the RegExp.test() method to check whether a string contains a substring. Here’s an example:

let str = "Example String!";

/Example/.test(str);

Our code returns true. This is because “JavaScript” is in our “example” string.

Regex is powerful. The downside to regex is that it can be slower to run depending on what rules you use. The more statements you add to your regex rules, the longer your search will take.

If you’re performing a simple search and have no need for advanced string functions, using includes() or indexOf() may be a better approach. The RegExp.test() method is not recommended for beginners who have not yet learned about Regex.

If you’re looking to learn more about regex and test out your regex, check out RegExr.

Conclusion

In this tutorial, we discussed the basics of strings in JavaScript. After that, we discussed three ways in which you can check if a string contains a substring in JavaScript: using includes(), indexOf(), and regex.

The includes() method is arguably the most common way of checking if a string contains a substring. This is because the name of the method is literal. It is clear includes() lets you search for a string inside another string.

Are you interested in learning more about JavaScript? We’ve got you covered. Check out our How to Learn JavaScript article for expert learning advice. You’ll also find a list of top learning resources to help you advance your knowledge.

Понравилась статья? Поделить с друзьями:
  • Java to excel macro
  • Javascript for excel export
  • Java split one word
  • Javascript find word in text
  • Java search for word