最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

how to check if text exists in javascript var - Stack Overflow

programmeradmin3浏览0评论

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.

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.

Share Improve this question asked Jan 24, 2011 at 17:58 jason45jason45 1332 gold badges3 silver badges6 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 6

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

Example: http://jsfiddle/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/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'.

发布评论

评论列表(0)

  1. 暂无评论