Reputation: 133
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.
Upvotes: 3
Views: 11268
Reputation: 71
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
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'.
Upvotes: 2
Reputation: 322492
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" );
Upvotes: 6
Reputation: 163238
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"
}
Upvotes: 5