Javascript 如何检查javascript变量是否包含字符串?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10345215/
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
How can I check if a javascript variable contains a string or not?
提问by Nagaraju Badaeni
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”?
回答by Nagaraju Badaeni
Use indexOf()
:
使用indexOf()
:
var str = $form.attr('action');
if(str.indexOf("JsonEdit")>=0){
//do something you want
}
回答by Joseph
You can use RegExp test
to check if you have something there. test
returns true if a match is found, and false if not.
您可以使用 RegExptest
检查那里是否有东西。test
如果找到匹配项,则返回 true,否则返回false。
if(/JsonEdit/.test(action)){
//there is something
}