admin管理员组

文章数量:1302545

I am trying to use contains to find out if a phrase appears within a string The code below works fine in FF and Chrome, however IE8-10 return an error.

SCRIPT438: Object doesn't support property or method 'contains'

var str = "This is a string";
if(str.contains("string")){
    alert('Yes'};
}

Not sure why IE is throwing a error so any help would be much appreciated.

I am trying to use contains to find out if a phrase appears within a string The code below works fine in FF and Chrome, however IE8-10 return an error.

SCRIPT438: Object doesn't support property or method 'contains'

var str = "This is a string";
if(str.contains("string")){
    alert('Yes'};
}

Not sure why IE is throwing a error so any help would be much appreciated.

Share Improve this question edited Nov 3, 2014 at 17:58 rink.attendant.6 46.3k64 gold badges110 silver badges157 bronze badges asked Nov 3, 2014 at 17:57 user3515428user3515428 592 silver badges4 bronze badges 2
  • 1 MDN String.contains First check documentation, then check Google. Asking someone for help es later down the line. – user1106925 Commented Nov 3, 2014 at 17:59
  • Also your alert probably should be alert('Yes'); not alert('Yes'}; with a brace. – phantom Commented Nov 3, 2014 at 18:00
Add a ment  | 

1 Answer 1

Reset to default 9

The .contains() function is an ES2015 feature that older Internet Explorer versions don't support.

The MDN page has a polyfill:

if ( !String.prototype.contains ) {
    String.prototype.contains = function() {
        return String.prototype.indexOf.apply( this, arguments ) !== -1;
    };
}

A general guide for questions like this: type MDN something into the Google search box. If you don't find a result, then "something" probably doesn't exist in the JavaScript universe. If you do, then there's a pretty good chance that you'll find the answer you seek there.

本文标签: javascriptString contains not working in IEStack Overflow