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

includes

ES6 introduced String.prototype.includes:

'foo'.includes('oo') // true
'foo'.includes('bar') // false

indexOf

includes doesn’t have IE support, though. In an ES5 or older environment, String.prototype.indexOf, which returns −1 when it doesn’t find the substring, can be used instead:

'foo'.indexOf('oo') // 1
'foo'.indexOf('bar') // -1

@Mark Amery 2019-04-16 13:58:58

@dimpiax, you've restored the example using match that Ry- deliberately chose to remove. Why? It's not necessarily wrong to have it here, but what advantage does it have over indexOf? What's the motivation for ever using it over one of the other two options? If there's no justification, then it probably isn't useful to include the option at all. If there is a justification, then it'd be helpful to include it in the answer. (Also, I don't like the example you've added, since it doesn't make clear that the argument to .match() is a regex; as written this lays a trap for the reader.)

@dimpiax 2019-04-17 11:07:53

@MarkAmery, you're right, in the current case – no reason to provide the example with function that accepts regex.

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

Another alternative is KMP.

The KMP algorithm provides worst-case linear time substring search, so it is a reasonable way if you do 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
}

Example usage:

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

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

Related Questions

Sponsored Content

78 Answered Questions

[SOLVED] How do I remove a particular element from an array in JavaScript?

  • 2011-04-23 22:17:18
  • Walker
  • 5650459 View
  • 7025 Score
  • 78 Answer
  • Tags:   javascript arrays

50 Answered Questions

[SOLVED] How to replace all occurrences of a string in JavaScript

82 Answered Questions

[SOLVED] How do I make the first letter of a string uppercase in JavaScript?

37 Answered Questions

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

36 Answered Questions

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

86 Answered Questions

[SOLVED] How do JavaScript closures work?

24 Answered Questions

[SOLVED] Case insensitive 'Contains(string)'

17 Answered Questions

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

22 Answered Questions

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

  • 2008-10-23 12:37:31
  • davidsheldon
  • 1653183 View
  • 2042 Score
  • 22 Answer
  • Tags:   string bash substring

53 Answered Questions

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

Sponsored Content