简体   繁体   English

如何检查javascript var中是否存在文本

[英]how to check if text exists in javascript var

I have a var that contains some text. 我有一个包含一些文本的var。 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/ 示例: 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: 如果您愿意,当然可以将其原型化为String:

Example: http://jsfiddle.net/JMjpY/1/ 示例: 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. 关于Jacob,'contains'功能中缺少Opening Bracket。

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

should be 应该

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

I have opted for Patricks Answer and adapted it into a function 我选择了Patricks Answer并将其改编成一个函数

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'. 这将返回False,因为尽管变量ManyWords中存在“单词”,但此函数仅显示“单词”的完全匹配。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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