Javascript 如何检查字符串是否存在于jquery中的变量中

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11732815/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 06:53:39  来源:igfitidea点击:

How to check if string is present in variable in jquery

javascript

提问by Mirage

I have the variable like

我有这样的变量

var myVar = "The man is running"

var myVar = "The man is running"

pattern = "run"

pattern = "run"

I want to check via jquery that if it conatins words "run"

我想通过 jquery 检查它是否包含“运行”字样

Like

喜欢

if($(myVar).(:contains(pattern)))
return true

Is this possible

这可能吗

回答by Ohgodwhy

RegExp option...just because..RegExp.

RegExp 选项...只是因为...RegExp。

var pattern = /run/;

//returns true or false...
var exists = pattern.test(myVar);

if (exists) {
  //true statement, do whatever
} else {
  //false statement..do whatever
}

回答by jeff

You would use the Javascript method .indexOf()to do this. If you're trying to test whether the text of a DOM element contains the pattern, you would use this:

您将使用 Javascript 方法.indexOf()来执行此操作。如果您尝试测试 DOM 元素的文本是否包含该模式,您可以使用以下命令:

if($(myVar).text().indexOf(pattern) != -1)
    return true;

If the variable myVarisn't a selector string, you shouldn't wrap it in the jQuery function, though. Instead, you would use this:

但是,如果变量myVar不是选择器字符串,则不应将其包装在 jQuery 函数中。相反,你会使用这个:

if(myVar.indexOf(pattern) != -1)
    return true;

回答by Paul Armstrong

You do not need jQuery for this. Just check for the index of the string.

为此,您不需要 jQuery。只需检查字符串的索引。

if (myVar.indexOf(pattern) !== -1) { ... }

if (myVar.indexOf(pattern) !== -1) { ... }

回答by elclanrs

Regex?

正则表达式?

var hasRun = /run/i.test(myVar) // case insensitive