Javascript string has value

JavaScript String Contains: Step-By-Step Guide

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.

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.

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:

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

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.

Читайте также:  Python вхождение во множество

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

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

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.

Читайте также:  Html input submit name php

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.

About us: Career Karma is a platform designed to help job seekers find, research, and connect with job training programs to advance their careers. Learn about the CK publication.

Читайте также:  Настройка php ini openserver

Источник

String.prototype.includes()

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

Синтаксис

str.includes(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; > >; > 

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

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

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() .

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

  • Array.prototype.includes() Экспериментальная возможность
  • TypedArray.prototype.includes() (en-US) Экспериментальная возможность
  • String.prototype.indexOf()
  • String.prototype.lastIndexOf()
  • String.prototype.startsWith()
  • String.prototype.endsWith()

Found a content problem with this page?

This page was last modified on 22 окт. 2022 г. by MDN contributors.

Источник

Оцените статью