3

I have a var that contains some text. I would like to check whether the texts has a certain word.

Example:

var myString = 'This is some random text';

I would like to check if the word "random" exists. Thanks for any help.

jason45
  • 123
  • 2
  • 3
  • 5

3 Answers3

6

If you want to test for the word "random" specifically, you can use a regular expression like this:

Example: http://jsfiddle.net/JMjpY/

var myString = 'This is some random text';
var word = 'random';
var regex = new RegExp( '\\b' + word + '\\b' );

var result = regex.test( myString );

This way it won't match where "random" is part of a word like "randomize".


And of course prototype it onto String if you wish:

Example: http://jsfiddle.net/JMjpY/1/

String.prototype.containsWord = function( word ) {
    var regex = new RegExp( '\\b' + word + '\\b' );
    return regex.test( this );
};

myString.containsWord( "random" );
user113716
  • 318,772
  • 63
  • 451
  • 440
  • I've been using this, but it doesnt seem to work with some characters, eg: -5 degrees (returns false with the minus) Any ideas to fix? – Ricky Jul 23 '11 at 19:08
  • @Ricky: You could do `new RegExp( '\\s|\\b' + word + '\\s|\\b' );`, but then if the string contains `-5 degrees`, it would give a positive result if searching for `5 degrees`. – user113716 Jul 23 '11 at 23:58
  • It seems to always return true now. – Ricky Jul 25 '11 at 18:40
  • 1
    @Ricky: I forgot to group them. `new RegExp( '(\\s|\\b)' + word + '(\\s|\\b)' )`. – user113716 Jul 29 '11 at 01:09
5

You can do it with a standalone function:

function contains(str, text) {
   return str.indexOf(text) >= 0);
}

if(contains(myString, 'random')) {
   //myString contains "random"
}

Or with a prototype extension:

String.prototype.contains = String.prototype.contains || function(str) {
   return this.indexOf(str) >= 0;
}

if(myString.contains('random')) {
   //myString contains "random"
}
Jacob Relkin
  • 161,348
  • 33
  • 346
  • 320
2

With respect to Jacob, There is a missing Opening Bracket in the 'contains' function.

return str.indexOf(text) >= 0);

should be

return (str.indexOf(text) >= 0);

I have opted for Patricks Answer and adapted it into a function

Example

function InString(myString,word)
    {
    var regex = new RegExp( '\\b' + word + '\\b' );
    var result = regex.test( myString );
    return( result );
    }

Call the Function with

var ManyWords='This is a list of words';
var OneWord='word';
if (InString(ManyWords,OneWord)){alert(OneWord+' Already exists!');return;}

This would return False because although 'words' exists in the variable ManyWords, this function shows only an exact match for 'word'.

MikeRG
  • 71
  • 1
  • 6