Javascript find word in text

Does Javascript have a built-in function to see if a word is present in a string? I’m not looking for something like indexOf(), but rather:

find_word('test', 'this is a test.') -> true
find_word('test', 'this is a test') -> true
find_word('test', 'I am testing this out') -> false
find_word('test', 'test this out please') -> true
find_word('test', 'attest to that if you would') -> false

Essentially, I’d like to know if my word appears, but not as part of another word. It wouldn’t be too hard to implement manually, but I figured I’d ask to see if there’s already a built-in function like this, since it seems like it’d be something that comes up a lot.

asked Aug 25, 2014 at 20:37

Mala's user avatar

5

You can use split and some:

function findWord(word, str) {
  return str.split(' ').some(function(w){return w === word})
}

Or use a regex with word boundaries:

function findWord(word, str) {
  return RegExp('\b'+ word +'\b').test(str)
}

answered Aug 25, 2014 at 20:39

elclanrs's user avatar

elclanrselclanrs

92.2k21 gold badges135 silver badges170 bronze badges

3

The JavaScript includes() method determines whether a string contains the characters of a specified string. This method returns true if the string contains the characters, and false if not.

Syntax:

string.includes(searchvalue, start)

Parameter values:

Parameter      Description
searchvalue    Required. The string to search for
start          Optional. Default 0. At which position to start the search

Example:

const sentence = 'The quick brown fox jumps over the lazy dog.';
const word = 'fox';
console.log(`The word "${word}" ${sentence.includes(word) ? 'is' : 'is not'} in the sentence`);

answered Sep 27, 2020 at 7:41

karel's user avatar

karelkarel

5,23943 gold badges45 silver badges50 bronze badges

Moderns browsers have the Array.prototype.includes(), which determines whether an array includes a certain value among its entries, returning true or false as appropriate.

Here’s an example:

const ShoppingList = ["Milk", "Butter", "Sugar"];

console.log(`Milk ${ShoppingList.includes("Milk") ? "is" : "is not"} in the shopping list.`);

console.log(`Eggs ${ShoppingList.includes("Eggs") ? "is" : "is not"} in the shopping list.`)

Jakye's user avatar

Jakye

6,4013 gold badges18 silver badges36 bronze badges

answered Sep 27, 2020 at 3:16

soufiane amabraa's user avatar

2

The search() method executes a search for a match between a regular expression and this String object.

Try it

Syntax

Parameters

regexp

A regular expression object, or any object that has a Symbol.search method.

If regexp is not a RegExp object and does not have a Symbol.search method, it is implicitly converted to a RegExp by using new RegExp(regexp).

Return value

The index of the first match between the regular expression and the given string, or -1 if no match was found.

Description

The implementation of String.prototype.search() itself is very simple — it simply calls the Symbol.search method of the argument with the string as the first parameter. The actual implementation comes from RegExp.prototype[@@search]().

The g flag of regexp has no effect on the search() result, and the search always happens as if the regex’s lastIndex is 0. For more information on the behavior of search(), see RegExp.prototype[@@search]().

When you want to know whether a pattern is found, and also know its index within a string, use search().

  • If you only want to know if it exists, use the RegExp.prototype.test() method, which returns a boolean.
  • If you need the content of the matched text, use match() or RegExp.prototype.exec().

Examples

Using search()

The following example searches a string with two different regex objects to show a successful search (positive value) vs. an unsuccessful search (-1).

const str = "hey JudE";
const re = /[A-Z]/;
const reDot = /[.]/;
console.log(str.search(re)); // returns 4, which is the index of the first capital letter "J"
console.log(str.search(reDot)); // returns -1 cannot find '.' dot punctuation

Specifications

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

Browser compatibility

BCD tables only load in the browser

See also

Теги: javascript, символ, поиск, методы, строка, индекс, проверка, строковые функции, слово, indexof

Для поиска слова, символа или любой другой подстроки в строке в языке программирования JavaScript используют хорошо известный метод indexOf. В результате проверки метод возвращает позицию первого совпадения, если же совпадение по введённому вами символу найдено не будет, будет возвращено -1.

JavaScriptPro_970x90-20219-f847d3.png

Искомое слово или символ указываются первым параметром. Что касается второго параметра, то он необязателен. Зато с его помощью мы можем передать номер (индекс) символа или буквы, с которого надо начинать поиск. Важный момент: метод indexOf() чувствителен к регистру вводимых вами букв, слов и символов.

Синтаксис метода предельно прост:

строка.indexOf(первый параметр указывает, что ищем, [второй параметр определяет, откуда начинаем поиск]);

Приведем примеры поиска слова в строке JavaScript

В примере ниже у нас есть строка ‘Я учусь в OTUS’, причём мы ищем в строке слово ‘учусь’. Метод вернёт нам индекс 2, т. к. именно с этой позиции начинается слово ‘учусь’ в строке. Тут стоит вспомнить, что индексация (подсчёт позиции) начинается с нуля, а не с единицы.

let str = 'Я учусь в OTUS;
console.log(str.indexOf('учусь'));

В результате получим следующий вывод:


В очередном примере в строке ‘Я учу Java и учу JavaScript в OTUS’ давайте найдём слово ‘учу’, но не первое его вхождение в строку, а второе. Следовательно, начнём поиск с 5-й позиции, указав это вторым параметром.

let str = 'Я учу Java и учу JavaScript в OTUS';
console.log(str.indexOf('учу', 5));

Проверка приведёт к возвращению числа 13, т. к. именно с этой позиции начинается второе слово «учу» в нашей строке.

Давайте приведем ещё парочку примеров. В коде ниже, исследуемый нами метод поиска вернёт -1, ведь подстроки ‘Go’ в нашей строке попросту нет:

let str = 'Я учусь в OTUS';
console.log(str.indexOf('Go'));

В принципе, как видите, ничего сложного. Нам вернётся -1 и в случае, если мы будем искать одинаковые слова с разным регистром (OTUS не равно OtuS):

let str = 'Я учусь в OTUS;
console.log(str.indexOf(' OtuS'));

Вернётся -1 и в последнем примере, ведь после позиции, которую мы выбрали вторым параметром для поиска, совпадения найдены не будут:

let str = 'Я учусь в OTUS';
console.log(str.indexOf('учусь', 7));

Проверка приведёт к следующему результату:


Вот и всё, что можно сказать про простейший поиск слов и символов в строке JavaScript. Напоследок стоит упомянуть метод lastIndexOf(), тоже осуществляющий поиск символа, слова или любой подстроки в строке. Разница заключается лишь в том, что этот метод начинает искать с конца строки, а не с начала — в остальном он работает аналогично.

Больше операций по поиску в строке JavaScript, включая дополнительные операции по работе с подстрокой, вы найдёте здесь.

Интересует профессиональный курс по JavaScript-разработке? Переходите по ссылке ниже:

JavaScriptPro_970x550-20219-412f62.png

You can use .includes() and check for the word. To make sure it is a word and not part of another word, verify that the place you found it in is followed by a space, comma, period, etc and also has one of those before it. You can .split() your string by spaces (s+) into an array, and then use .includes() to check if the array of strings has your word within it: So, you can easily check if a string contains a particular substring using the .includes() method. You first need to convert it into array using split() and then use includes()

This is our Splunktool team suggestion ✌, we tried and its working fine

var str = "This is a test sentence";
var hasTest = str.includes("test");

You first need to convert it into array using split() and then use includes()

string.split(" ").includes("on")

3._

function checkWord(word, str) {
   const allowedSeparator = '\s,;"'|';

   const regex = new RegExp(
      `(^.*[${allowedSeparator}]${word}$)|(^${word}[${allowedSeparator}].*)|(^${word}$)|(^.*[${allowedSeparator}]${word}[${allowedSeparator}].*$)`,

      
      'i',
   );

   return regex.test(str);
}

[
   'phones are good',
   'keep it on the table',
   'on',
   'keep iton the table',
   'keep it on',
   'on the table',
   'the,table,is,on,the,desk',
   'the,table,is,on|the,desk',
   'the,table,is|the,desk',
].forEach((x) => {
   console.log(`Check: ${x} : ${checkWord('on', x)}`);
});

Suggestion : 2

Find a top-rated training program

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.

Find the right bootcamp for you

2._

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.");
}

3._

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");
}

5._

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.");
}

6._

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

str.indexOf(ourSubstring);

Suggestion : 3

Write a JavaScript function to find a word within a string.
Test Data:
console.log(search_word(‘The quick brown fox’, ‘fox’));
console.log(search_word(‘aa, bb, cc, dd, aa’, ‘aa’));
Output:
«‘fox’ was found 1 times.»
«‘aa’ was found 2 times.» Previous: Write a JavaScript function to convert Hexadecimal to ASCII format.
Next: Write a JavaScript function check if a string ends with specified suffix.

Sample Solution:-

HTML Code:

<!DOCTYPE html>
<html>

<head>
   <meta charset="utf-8">
   <title>JavaScript function to find a word within a string</title>
</head>

<body>

</body>

</html>

JavaScript Code:

function search_word(text, word) {

   var x = 0,
      y = 0;

   for (i = 0; i < text.length; i++) {
      if (text[i] == word[0]) {
         for (j = i; j < i + word.length; j++) {
            if (text[j] == word[j - i]) {
               y++;
            }
            if (y == word.length) {
               x++;
            }
         }
         y = 0;
      }
   }
   return "'" + word + "' was found " + x + " times.";
}

console.log(search_word('The quick brown fox', 'fox'));
console.log(search_word('aa, bb, cc, dd, aa', 'aa'));

Sample Output:

'fox'
was found 1 times.
'aa'
was found 2 times.

You can avoid it like this

const found = [{
   name: "Owen"
}].find(i => i.name === 'Kim') || {};
console.log(found.name);

Suggestion : 4

Syntax breakdown of the indexOf() method in JavaScript

How to check if a string contains a specific substring using the indexOf() method

index0f() is the method you call on the word you want to search through, in this case, string. includes() is the method you call on the word you want to search through, which in this case is string. string is the word you want to search through.

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 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";

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));


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

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

Suggestion : 5

This method lets you determine whether or not a string includes another string. true if the search string is found anywhere within the given string, including when searchString is an empty string; otherwise, false. You can work around this constraint by transforming both the original string and the search string to all lowercase: The includes() method is case sensitive. For example, the following expression returns false:

1._

includes(searchString)
includes(searchString, position)

2._

"Blue Whale".includes("blue"); 

3._

"Blue Whale".toLowerCase().includes("blue"); 

Suggestion : 6

The search() method executes a search for a match between a regular expression and this String object. String.prototype.search() The following example searches a string with two different regex objects to show a successful search (positive value) vs. an unsuccessful search (-1). Learn to style content using CSS

2._

const str = "hey JudE";
const re = /[A-Z]/;
const reDot = /[.]/;
console.log(str.search(re)); 
console.log(str.search(reDot)); 

Suggestion : 7

You want to check whether a string contains a substring in JavaScript. What are the different ways to do this? The indexOf() method is also case sensitive, and returns the index position of the first occurrence of the substring within the string. If the substring is not found, it returns -1. You can also include the position at which to begin searching the string for the substring. The default position is 0. charAt(index) – Returns a string representing the character at the specified index. If the index is out of range, it returns an empty string.

You can use JavaScript’s includes() method to check whether a string contains a substring. This will return true if the substring is found, or false if not.

Consider the code example below:

const str = 'This is my example string!';
const substr = 'my';

console.log(str.includes(substr));

The above code would output true.

Note that includes() performs a case-sensitive search. To work around this, you can convert the string to lower case using toLowerCase() as follows:

console.log(str.toLowerCase().includes(substr));

Furthermore, a position can also be passed as an argument to specify the position at which to begin searching the string for the substring. The default position is 0. If you want to begin searching at position 2, you would write:

console.log(str.includes(substr, 2));

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

Like this post? Please share to your friends:
  • Java search for word
  • Javascript excel в браузере
  • Java regex word or word
  • Javascript excel to json
  • Java regex for any word