简体   繁体   English

如何检查javascript变量是否包含字符串?

[英]How can I check if a javascript variable contains a string or not?

I have a variable: $form.attr('action') that contains one of the following: 我有一个变量:$ form.attr('action')包含以下之一:

action="/Administration/Contents/JsonCreate"
action="/Administration/Contents/JsonEdit"
action="/Administration/Contents/JsonDelete"

How can I with an if () statement check to see if it contains the word "JsonEdit" ? 如何使用if()语句检查它是否包含单词“ JsonEdit”?

Use indexOf() : 使用indexOf()

var str = $form.attr('action');

if(str.indexOf("JsonEdit")>=0){
    //do something you want
}

You can use RegExp test to check if you have something there. 您可以使用RegExp test来检查那里是否有东西。 test returns true if a match is found , and false if not. 如果找到匹配项,则 test 返回true,否则返回 false。

if(/JsonEdit/.test(action)){
    //there is something
}

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

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