-2

This is my JavaScript code :

var a = 'how are you';
if (a.indexOf('r') > -1) 
{
    alert('yes');
} 
else {
    alert('no');
}

This code alert('yes'). It only matches the character 'r' is present in the string or not. But I want to match a full word(like 'are') not a character. How I can do this?

Grijesh Chauhan
  • 57,103
  • 20
  • 141
  • 208
bd_person
  • 23
  • 1
  • 1
  • 6

3 Answers3

1

Read MDS

str.indexOf(searchValue[, fromIndex])

searchValue

A string representing the value to search for.

fromIndex
The location within the calling string to start the search from. It can be any integer between 0 and the length of the string. The default value is 0.

So (a.indexOf('are') > -1) should work that will return 4 for a = 'how are you'.

Grijesh Chauhan
  • 57,103
  • 20
  • 141
  • 208
0

like this

var str = "how are you";
var n = str.search("are");

or do u want algorithm?

Ashley Medway
  • 7,151
  • 7
  • 49
  • 71
HOO
  • 11
  • 3
0

You can also use a.search("are").

var a = 'how are you';
if (a.search('are') > -1) 
{
  alert('yes');
} 
else {
  alert('no');
}