Javascript search 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

Теги: 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

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

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

We have many times observed the yellow highlight around the string and as a programmer tried to think how can it possibly be able to mark all search words in a document that too in split milli-seconds. And after crawling the web and going through posts written by high skilled and experienced programmers I was able to achieve this goal. In this post will be on using regular expressions in highlighting the searched patterns inside the string.

Table of Contents

  • Introduction
  • Using RegEx object
  • Highlighting searched words
  • Conclusion

Introduction

Before this, we have done posts on string searching and replacing string which selective words. But this post is different from the rest of those as we’ll not only search but also, highlight searched words.

Using RegEx object

Regular expressions are a great way to get the desired output from matching words in a string. In javascript, we can create regular expression object using RegExp a class which takes pattern and flags as an argument.

Syntax

new RegExp(search_pattern, search_flags);
  • search_pattern: These include regular expression characters for searching in strings.
  • search_flags: In Regular Expression, flags act as a configuration which will determine the result or output.
    Some of the flags are given below:
    • g (global match) : This flag finds matches throughout the string.
    • i (disregards matched character or word case) : This flag will ignore the case of the matched string.

Create a simple search using RegExp

let string = "The best way to cheer yourself up is to try to cheer somebody else up.";
let pattern = 'self|body', flags='gmi';
let new_regexp = new RegExp(pattern, flags)
console.log(new_regexp.exec(string));
console.log(string.match(new_regexp));

// Console Output
["self", index: 26, input: "The best way to cheer yourself up is to try to cheer somebody else up.", groups: undefined]
(2) ["self", "body"]

Searching within string using RegEx in Javascript

Searching within a string using RegEx in Javascript

The new_regexp is an object created using class RegExp. Using the method .exec() we can check if the pattern exists in a string.
If a pattern exists that array is returned and if does not exists then null is returned.

Highlighting searched words

   
<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width">
        <title>repl.it</title>

        <style>
        #search_text{
            height: 30px;
            width: 200px;
        }
        </style>
    </head>
    <body>
        <p id="sentence" >There are many variations of passages of Lorem Ipsum available, but the majority have suffered alteration in some form, by injected humour, or randomised words which don't look even slightly believable. If you are going to use a passage of Lorem Ipsum, you need to be sure there isn't anything embarrassing hidden in the middle of text. All the Lorem Ipsum generators on the Internet tend to repeat predefined chunks as necessary, making this the first true generator on the Internet. It uses a dictionary of over 200 Latin words, combined with a handful of model sentence structures, to generate Lorem Ipsum which looks reasonable. The generated Lorem Ipsum is therefore always free from repetition, injected humour, or non-characteristic words etc.</p>
        <input onkeyup="hightlightSearchResult()"  id="search_text" type="text" placeholder="Search..." value="" >

        <script type="text/javascript" >
            let sentence_element = document.getElementById('sentence');
            let search_text_element = document.getElementById('search_text');
            let sentence_element_html = sentence_element.innerHTML;

            function hightlightSearchResult() {
                let search_text_value = search_text_element.value;
                search_text_value = search_text_value.replace(/[.*+?^${}()|[]]/g, '$&'); //https://stackoverflow.com/questions/3446170/escape-string-for-use-in-javascript-regex
                let regex_object = new RegExp(search_text_value, 'gi');
                if (search_text_value.length > 0){
                    sentence_element.innerHTML = sentence_element_html.replace(regex_object, `<mark>$&</mark>`);
                }else{
                    sentence_element.innerHTML = sentence_element_html;
                }
            }
        </script>
    </body>
</html>

Search and highlight words in Javascript

Search and highlight words in Javascript

Function hightlightSearchResult() is triggered on keyup event. regex_object is a regular expression object
which we can use to check searched_text_value exists in the paragraph.

Note

$& in regular expression get the lastMatch of searched value.

Conclusion

We have come to the end of our post on JavaScript Search and Highlight Words within String. If you like our content then please do share it and comment to clarify your doubts.

Related Posts

  • JavaScript Tips for Array Looping and Iteration for Beginners
  • JavaScript | Accessing and Manipulating DOM Elements for Beginners

Summary

Review Date

2020-12-04

Reviewed Item

JavaScript Search and Highlight Words within String

Author Rating

51star1star1star1star1star

Software Name

Javascript Programming

Software Name

Windows Os, Mac Os, Ubuntu Os

Software Category

Web Development

Like this post? Please share to your friends:
  • Java word to text
  • Javascript reading excel file
  • Java word to number one
  • Java word for number
  • Javascript if word is in string