29
$a = 'how are you';
if (strpos($a,'are') !== false) {
    echo 'true';
}

In PHP, we can use the code above to check if a string contain specific words, but how can I do the same function in JavaScript/jQuery?

j08691
  • 197,815
  • 30
  • 248
  • 265
Charles Yeung
  • 37,627
  • 28
  • 87
  • 130
  • 2
    possible duplicate of [javascript : string contains ...](http://stackoverflow.com/questions/1789945/javascript-string-contains) – Jørn Schou-Rode Mar 22 '11 at 08:20
  • 2
    and [JQuery string contains check](http://stackoverflow.com/questions/3728022/jquery-string-contains-check) – Jørn Schou-Rode Mar 22 '11 at 08:21
  • 1
    Possible duplicate of [How to see if string contains substring](http://stackoverflow.com/questions/3480771/how-to-see-if-string-contains-substring) – Shafizadeh Nov 30 '15 at 17:08

10 Answers10

66

you can use indexOf for this

var a = 'how are you';
if (a.indexOf('are') > -1) {
  return true;
} else {
  return false;
}

Edit: This is an old answer that keeps getting up votes every once in a while so I thought I should clarify that in the above code, the if clause is not required at all because the expression itself is a boolean. Here is a better version of it which you should use,

var a = 'how are you';
return a.indexOf('are') > -1;

Update in ECMAScript2016:

var a = 'how are you';
return a.includes('are');  //true
Santhoshkumar
  • 738
  • 1
  • 18
  • 34
naiquevin
  • 7,238
  • 12
  • 51
  • 62
  • 5
    very bad answer. this will fail: 'howare you' – vsync Jan 12 '14 at 23:29
  • @vsync Why you said "bad answer"? Because he removed IF-statement? Well, what is your opinion about pre-edited? (before editing) – Shafizadeh Nov 30 '15 at 15:15
  • 1
    @Shafizadeh - not because of the `if`. did you even read my answer to understand why using `indexof` is bad in this context? why did you even think it's because if the `if` anyway? – vsync Nov 30 '15 at 16:43
38

indexOf/includes should not be used for finding whole words:

A word (in western culture) is a drawing of a symbols close to each other, with some space between each word. A word is considered as such if it's a complete piece of characters draw together and not a partial part of it:

"has a word".indexOf('wor')  // 6 ("wor" is not a word in this sentence)
"has a word".includes('ha') // true ("ha" is not a word in this sentence)

Check if a single word (whole word) is in the string

Find a real whole word, not just if the letters of that word are somewhere in the string.

const wordInString = (s, word) => new RegExp('\\b' + word + '\\b', 'i').test(s);

// tests
[
  '',            // true
  ' ',           // true
  'did',         // true
  'id',          // flase
  'yo ',         // flase
  'you',         // true
  'you not'      // true
].forEach(q => console.log(
  wordInString('dID You, or did you NOt, gEt WHy?', q) 
))

console.log(
  wordInString('did you, or did you not, get why?', 'you') // true
)

Check if all words are in the string

var stringHasAll = (s, query) => 
  // convert the query to array of "words" & checks EVERY item is contained in the string
  query.split(' ').every(q => new RegExp('\\b' + q + '\\b', 'i').test(s)); 


// tests
[
  '',            // true
  ' ',           // true
  'aa',          // true
  'aa ',         // true
  ' aa',         // true
  'd b',         // false
  'aaa',         // false
  'a b',         // false
  'a a a a a ',  // false
].forEach(q => console.log(
  stringHasAll('aA bB cC dD', q) 
))
vsync
  • 103,437
  • 51
  • 275
  • 359
  • 1
    I had a chance where I need 2 check if "How are you?", "Are you crazy?" contains the string "are"(case insensitively) and not contains "Awareness is important". In such a case, this function is so helpful @vsync :) – SriramK89 Apr 25 '14 at 12:24
  • 1
    Make sure the "word" does not contain any regex meta characters or the match will not work. Any regex meta characters in the word must be escaped. – Stephen Chung Aug 08 '14 at 09:17
  • +1 for adding the way to make the word you're looking for a variable. Most other answers I found offered a fix pattern... – patrick Sep 06 '15 at 13:37
  • Well I read your answer and it can be fine :-) ! +1. btw I think using `indexOf` is fine either, because [here](http://stackoverflow.com/questions/3480771/how-to-see-if-string-contains-substring#3480785) and [here](http://stackoverflow.com/questions/1789945/how-can-i-check-if-one-string-contains-another-substring#1789952) are two great answers from two profesional persons that both of him have used `indexOf`. – Shafizadeh Nov 30 '15 at 17:07
  • 1
    @Shafizadeh - those answers you have referred to do not apply to this specific question, where an `indexOf` solution will fail, regardless of how "professional" those who gave those answers are. – vsync Nov 30 '15 at 19:54
  • Would be nice to complete this answer with the case if you need to check some words in the string. In general you need to change this string `query.split(' ').every(q => new RegExp('\\b' + q + '\\b', 'i').test(s)); ` to this `query.split(' ').filter(String).some(q => new RegExp('\\b' + q + '\\b', 'i').test(s)); `. You need to filter the query for removing the empty strings like `''` from array like `['a', '', '']` in case the query is `a ` because empty string is a substring of any string. – Experimenter Nov 12 '21 at 22:11
27

If you are looking for exact words and don't want it to match things like "nightmare" (which is probably what you need), you can use a regex:

/\bare\b/gi

\b = word boundary
g = global
i = case insensitive (if needed)

If you just want to find the characters "are", then use indexOf.

If you want to match arbitrary words, you have to programatically construct a RegExp (regular expression) object itself based on the word string and use test.

Stephen Chung
  • 14,353
  • 1
  • 33
  • 47
8

You're looking for the indexOf function:

if (str.indexOf("are") >= 0){//Do stuff}
evbailey
  • 351
  • 3
  • 10
6

You might wanna use include method in JS.

var sentence = "This is my line";
console.log(sentence.includes("my"));
//returns true if substring is present.

PS: includes is case sensitive.

Neelansh Verma
  • 134
  • 1
  • 6
4

In javascript the includes() method can be used to determines whether a string contains particular word (or characters at specified position). Its case sensitive.

var str = "Hello there."; 

var check1 = str.includes("there"); //true
var check2 = str.includes("There"); //false, the method is case sensitive
var check3 = str.includes("her");   //true
var check4 = str.includes("o",4);   //true, o is at position 4 (start at 0)
var check5 = str.includes("o",6);   //false o is not at position 6
Zeni
  • 807
  • 1
  • 9
  • 20
3

An easy way to do it to use Regex match() method :-

For Example

var str ="Hi, Its stacks over flow and stackoverflow Rocks."

// It will check word from beginning to the end of the string

if(str.match(/(^|\W)stack($|\W)/)) {

        alert('Word Match');
}else {

        alert('Word not found');
}

Check the fiddle

NOTE: For adding case sensitiveness update the regex with /(^|\W)stack($|\W)/i

Thanks

Vineeth Sai
  • 3,262
  • 7
  • 20
  • 31
2

This will

/\bword\b/.test("Thisword is not valid");

return false, when this one

/\bword\b/.test("This word is valid");

will return true.

Jahid
  • 19,822
  • 8
  • 86
  • 102
2

var str1 = "STACKOVERFLOW";
var str2 = "OVER";
if(str1.indexOf(str2) != -1){
    console.log(str2 + " found");
}
pgksunilkumar
  • 141
  • 1
  • 4
0

Using a conditional ternary operator

str = 'I am on StackOverflow';
str.match(/(^|\W)StackOverflow($|\W)/) ? 'Found. Why lie?' : 'Not Found';
WiiLF
  • 164
  • 2
  • 11