简体   繁体   中英

how to check if text exists in javascript var

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.

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

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"
}

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'.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM