jQuery 如果在字符串中找到

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1287910/
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-26 11:06:45  来源:igfitidea点击:

jQuery if found in string

jqueryif-statement

提问by Ronal

How can I have jQuery check to see if the content of a variable contains a specific word and have it execute an alert if matched?

如何让 jQuery 检查变量的内容是否包含特定单词,并在匹配时执行警报?

采纳答案by TM.

If you are looking to check a javascript variableand not some element on the page, jQuery isn't going to really make it any easier/different than using plain javascript.

如果您想检查 javascript变量而不是页面上的某些元素,jQuery 不会真正使它比使用普通 javascript 更容易/不同。

The other answers mentioned here using regex will work, but you might want to look at the String object referenceor the RegExp object referenceat w3schools, if you want to understand it better.

此处提到的使用正则表达式的其他答案将起作用,但如果您想更好地理解它,您可能需要查看w3schools上的String 对象引用RegExp 对象引用

回答by geowa4

if( str.indexOf( "your word" ) !== -1 )

or

或者

if( str.search( /your regex/ig ) )

or

或者

if( str.match( /your regex/ig ).length > 0 )

As it shows, you do not need jQuery to solve this problem.

正如它所显示的,您不需要 jQuery 来解决这个问题。

But, hell, why not use jQuery selectorsif you want:

但是,见鬼,如果您愿意,为什么不使用jQuery 选择器

$('#someId:contains(text)')

回答by TM.

One word: Regular expressions.

一个字:正则表达式。

Whoops, that were 2 words ;)

哎呀,那是 2 个字 ;)

https://developer.mozilla.org/en/Core_JavaScript_1.5_Guide/Regular_Expressions

https://developer.mozilla.org/en/Core_JavaScript_1.5_Guide/Regular_Expressions

Regex:

正则表达式:

/.(mystring\swhich\sshould\smatch)./

回答by raptors

For an element, use String functions on its name or whatever other applicable attribute value:

对于元素,在其名称或任何其他适用的属性值上使用字符串函数:

if(jQuery("elementName").attr("attributeName").contains(...))
  callSomeJSFunction();

, or Regular Expressions. If it's something simple, string manipulation should be sufficient as other people have mentioned. Another great resource are the jQuery API pagesor countless other tutorials found through a Google search. Google's groups are often another useful resource.

,或正则表达式。如果它很简单,那么字符串操作就足够了,就像其他人提到的那样。另一个很棒的资源是jQuery API 页面或通过 Google 搜索找到的无数其他教程。Google 的群组通常是另一种有用的资源。