Check string in string javascript

Examples

Check if a string includes "world":

let text = "Hello world, welcome to the universe.";
let result = text.includes("world");

Try it Yourself »

let text = "Hello World, welcome to the universe.";
let result = text.includes("world", 12);

Try it Yourself »

More examples below.


Definition and Usage

The includes() method returns true if a string contains a specified string.

Otherwise it returns false.

The includes() method is case sensitive.


Syntax

string.includes(searchvalue, start)

Parameters

Parameter Description
searchvalue Required.
The string to search for.
start Optional.
The position to start from.
Default value is 0.

Return Value

Type Description
A boolean. true if the string contains the value, otherwise false.


More Examples

Start at position 12:

let text = "Hello world, welcome to the universe.";
let result = text.includes("world", 12);

Try it Yourself »


Browser Support

includes() is an ECMAScript6 (ES6) feature.

ES6 (JavaScript 2015) is supported in all modern browsers:

Chrome Edge Firefox Safari Opera
Yes Yes Yes Yes Yes

includes() is not supported in Internet Explorer 11 (or earlier).



Another alternative is KMP (Knuth–Morris–Pratt).

The KMP algorithm searches for a length-m substring in a length-n string in worst-case O(n+m) time, compared to a worst-case of O(n⋅m) for the naive algorithm, so using KMP may be reasonable if you care about worst-case time complexity.

Here's a JavaScript implementation by Project Nayuki, taken from https://www.nayuki.io/res/knuth-morris-pratt-string-matching/kmp-string-matcher.js:

// Searches for the given pattern string in the given text string using the Knuth-Morris-Pratt string matching algorithm.
// If the pattern is found, this returns the index of the start of the earliest match in 'text'. Otherwise -1 is returned.

function kmpSearch(pattern, text) {
  if (pattern.length == 0)
    return 0; // Immediate match

  // Compute longest suffix-prefix table
  var lsp = [0]; // Base case
  for (var i = 1; i < pattern.length; i++) {
    var j = lsp[i - 1]; // Start by assuming we're extending the previous LSP
    while (j > 0 && pattern[i] !== pattern[j])
      j = lsp[j - 1];
    if (pattern[i] === pattern[j])
      j++;
    lsp.push(j);
  }

  // Walk through text string
  var j = 0; // Number of chars matched in pattern
  for (var i = 0; i < text.length; i++) {
    while (j > 0 && text[i] != pattern[j])
      j = lsp[j - 1]; // Fall back in the pattern
    if (text[i]  == pattern[j]) {
      j++; // Next char matched, increment position
      if (j == pattern.length)
        return i - (j - 1);
    }
  }
  return -1; // Not found
}

console.log(kmpSearch('ays', 'haystack') != -1) // true
console.log(kmpSearch('asdf', 'haystack') != -1) // false

The includes() method performs a case-sensitive search to determine whether one string may be found within another string, returning true or false as appropriate.

Try it

Syntax

includes(searchString)
includes(searchString, position)

Parameters

searchString

A string to be searched for within str. Cannot be a regex.

position Optional

The position within the string at which to begin searching for searchString. (Defaults to 0.)

Return value

true if the search string is found anywhere within the given string; otherwise, false if not.

Exceptions

Description

This method lets you determine whether or not a string includes another string.

Case-sensitivity

The includes() method is case sensitive. For example, the following expression returns false:

'Blue Whale'.includes('blue')  // returns false

You can work around this constraint by transforming both the original string and the search string to all lowercase:

'Blue Whale'.toLowerCase().includes('blue')  // returns true

Examples

Using includes()

const str = 'To be, or not to be, that is the question.'

console.log(str.includes('To be'))        // true
console.log(str.includes('question'))     // true
console.log(str.includes('nonexistent'))  // false
console.log(str.includes('To be', 1))     // false
console.log(str.includes('TO BE'))        // false
console.log(str.includes(''))             // true

Specifications

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

Browser compatibility

BCD tables only load in the browser

See also

How do you check if a string contains a string in JavaScript?

To check if a substring is contained in a JavaScript string: Call the indexOf method on the string, passing it the substring as a parameter - string. indexOf(substring) Conditionally check if the returned value is not equal to -1. If the returned value is not equal to -1 , the string contains the substring.

How do you check if a string contains a character JavaScript?

In JavaScript, includes() method determines whether a string contains the given characters within it or not. This method returns true if the string contains the characters, otherwise, it returns false.

Can we use == to compare strings in JavaScript?

In JavaScript, strings can be compared based on their “value”, “characters case”, “length”, or “alphabetically” order: To compare strings based on their values and characters case, use the “Strict Equality Operator (===)”.

Is string check in JavaScript?

Check if a Variable is a String in JavaScript # We used the typeof operator to check if a variable is a string. The operator returns a string that indicates the type of the value. Copied! If the variable stores a string, the equality condition will return true and the if block will run.