By gramm


2009-11-24 13:04:29 8 Comments

Usually I would expect a String.contains() method, but there doesn't seem to be one.

What is a reasonable way to check for this?

3 comments

@Fabien Ménager 2009-11-24 13:05:36

ECMAScript 6 introduced String.prototype.includes:

const string = "foo";
const substring = "oo";

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

includes doesn’t have Internet Explorer support, though. In ECMAScript 5 or older environments, use String.prototype.indexOf, which returns -1 when a substring cannot be found:

var string = "foo";
var substring = "oo";

console.log(string.indexOf(substring) !== -1);

@rob74 2019-05-24 11:18:20

I don't like IE either, but if you have two functions that are largely identical, and one is better supported than the other one, I think you should pick the better supported one? So indexOf() it is...

@Eric McWinNEr 2019-06-26 16:32:13

Is it possible to do a case insensitive search?

@Rodrigo Pinto 2019-06-26 20:35:47

string.toUpperCase().includes(substring.toUpperCase())

@Code Maniac 2019-07-06 04:23:23

@EricMcWinNEr /regexpattern/i.test(str) --> i flag stands for case insensitivity

@Ryan 2019-08-28 15:06:27

This doesn't seem to work for me in Google App Script.

@Mohandes 2020-01-22 07:40:17

What if we check letters in a string? for example: check if "sample string" contains "elpmag" letters.

@Jay Dadhania 2020-05-21 11:50:16

@Mohandes If you want to check if at least one of these letters is there, you can use /[elpmag]/.test(myString) or if you need a case-insensitive match, /[elpmag]/i.test(myString)

@wz366 2017-07-05 22:26:38

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(nm) 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.charAt(i) != pattern.charAt(j))
      j = lsp[j - 1];
    if (pattern.charAt(i) == pattern.charAt(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.charAt(i) != pattern.charAt(j))
      j = lsp[j - 1]; // Fall back in the pattern
    if (text.charAt(i) == pattern.charAt(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

@Faissaloo 2020-01-08 14:33:28

This is overkill but nonetheless an interesting answer

@eliocs 2013-01-07 10:23:16

There is a String.prototype.includes in ES6:

"potato".includes("to");
> true

Note that this does not work in Internet Explorer or some other old browsers with no or incomplete ES6 support. To make it work in old browsers, you may wish to use a transpiler like Babel, a shim library like es6-shim, or this polyfill from MDN:

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

@Derk Jan Speelman 2019-06-03 14:40:39

Just do "potato".includes("to"); and run it through Babel.

@Sweet Chilly Philly 2019-11-18 00:25:30

includes isn't supported by IE sadly

@sejn 2020-04-18 05:40:39

@eliocs can you answer this. I am getting any one message. Need to change the message stackoverflow.com/questions/61273744/…

@Jonatas CD 2020-04-27 10:58:21

another plus for it is that is case sensitive as well. "boot".includes("T") is false

Related Questions

Sponsored Content

26 Answered Questions

[SOLVED] How to check if a string contains a substring in Bash

64 Answered Questions

[SOLVED] How to replace all occurrences of a string?

94 Answered Questions

[SOLVED] How can I remove a specific item from an array?

  • 2011-04-23 22:17:18
  • Walker
  • 6678705 View
  • 8258 Score
  • 94 Answer
  • Tags:   javascript arrays

57 Answered Questions

[SOLVED] How do I check if an element is hidden in jQuery?

39 Answered Questions

[SOLVED] var functionName = function() {} vs function functionName() {}

86 Answered Questions

[SOLVED] How do JavaScript closures work?

10 Answered Questions

[SOLVED] Does Python have a string 'contains' substring method?

66 Answered Questions

[SOLVED] How do I check whether a checkbox is checked in jQuery?

25 Answered Questions

[SOLVED] Case insensitive 'Contains(string)'

36 Answered Questions

[SOLVED] How do I check if a string contains a specific word?

Sponsored Content