-2

Possible Duplicate:
JavaScript: string contains

I want to search a string in javascript to see if it contain some characters

<script type="text/javascript">
var s="hello world";
if(s.contains("hello")) alert("contains");
</script>

I may expect a function like string.contains() . Is their a string.contains in javascript or should i use indexOf instead

Community
  • 1
  • 1
Sora
  • 2,465
  • 18
  • 73
  • 146

4 Answers4

1

If you really want a contains:

String.prototype.contains = function (searchTerm) {
    return this.toString().indexOf(searchTerm) !== -1;
};

If you're feeling fancy:

String.prototype.contains = function (searchTerm) {
    return ~this.toString().indexOf(searchTerm);
};
jbabey
  • 45,965
  • 12
  • 71
  • 94
0

indexOf is the way to go - just check the return value.

Dhaivat Pandya
  • 6,499
  • 4
  • 29
  • 43
0

Try regEx:

if( /hello/.test(s) )
    alert("contains");
David Hellsing
  • 106,495
  • 44
  • 176
  • 212
0
s.indexOf('hello') > -1

(docs) or

s.match('hello') === true

(docs, Be aware, that 'hello' will be interpreted as regular expression in this case.)

Boldewyn
  • 81,211
  • 44
  • 156
  • 212