How do you find a certain word in a string javascript?

$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

199k31 gold badges252 silver badges267 bronze badges

asked Mar 22, 2011 at 8:18

Charles YeungCharles Yeung

37.8k29 gold badges87 silver badges130 bronze badges

4

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

answered Mar 22, 2011 at 8:22

3

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) 
))

answered Jan 12, 2014 at 23:41

vsyncvsync

107k53 gold badges285 silver badges370 bronze badges

6

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.

answered Mar 22, 2011 at 8:27

Stephen ChungStephen Chung

14.4k1 gold badge33 silver badges48 bronze badges

You're looking for the indexOf function:

if (str.indexOf("are") >= 0){//Do stuff}

answered Mar 22, 2011 at 8:22

How do you find a certain word in a string javascript?

evbaileyevbailey

3713 silver badges11 bronze badges

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.

answered Apr 16, 2018 at 7:26

How do you find a certain word in a string javascript?

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

answered Oct 20, 2019 at 8:09

ZeniZeni

8371 gold badge10 silver badges22 bronze badges

1

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

How do you find a certain word in a string javascript?

Vineeth Sai

3,2727 gold badges22 silver badges32 bronze badges

answered Sep 20, 2018 at 6:33

How do you find a certain word in a string javascript?

This will

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

return false, when this one

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

will return true.

answered Jun 19, 2015 at 17:07

How do you find a certain word in a string javascript?

JahidJahid

20.4k8 gold badges89 silver badges104 bronze badges

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

answered Aug 29, 2018 at 6:09

How do you find a certain word in a string javascript?

Using a conditional ternary operator

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

answered Jan 21 at 20:28

WiiLFWiiLF

1642 silver badges11 bronze badges

If you'd like to find a single word in a string without regular expressions, you can do as follows:

function isWordInString(needle, haystack) {
  return haystack
    .split(' ')
    .some(p => (p === needle));
}
isWordInString('hello', 'hello great world!'); // true
isWordInString('eat', 'hello great world!'); // false

Advantages over regex:

  • Works with non-latin characters like Hebrew
  • No need to sanitize the word you search in the string. Some methods in other answers will fail and return a false positive when searching for a "." (dot)

answered Jun 8 at 9:42

How do you find a certain word in a string javascript?

ArikArik

4,8021 gold badge25 silver badges25 bronze badges

How do I check if a string contains a specific word in JavaScript?

The includes() method returns true if a string contains a specified string. Otherwise it returns false .

How do I find a specific word in a string?

To find a word in the string, we are using indexOf() and contains() methods of String class. The indexOf() method is used to find an index of the specified substring in the present string. It returns a positive integer as an index if substring found else returns -1.

How do I search for a word in JavaScript?

The search() method returns the index (position) of the first match. The search() method returns -1 if no match is found. The search() method is case sensitive.

How do you find a specific character in a string JavaScript?

JavaScript String indexOf() The indexOf() method returns the position of the first occurrence of a value in a string. The indexOf() method returns -1 if the value is not found. The indexOf() method is case sensitive.