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

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

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

javascript

提问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 testto check if you have something there. testreturns true if a match is found, and false if not.

您可以使用 RegExptest检查那里是否有东西。test如果找到匹配项,则返回 true,否则返回false。

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