如何检查javascript var中是否存在文本 [英] how to check if text exists in javascript var

查看:75
本文介绍了如何检查javascript var中是否存在文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含一些文字的var。我想检查文本是否有某个单词。

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

示例:

var myString = 'This is some random text';

我想检查随机这个词是否存在。感谢您的帮助。

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

推荐答案

如果您想特别测试单词random,可以使用正则表达式这个:

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

示例: 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".

如果您愿意,当然可以将其原型化为String:

And of course prototype it onto String if you wish:

示例: http://jsfiddle.net/JMjpY/1/

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

myString.containsWord( "random" );

这篇关于如何检查javascript var中是否存在文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆