Javascript JQuery 字符串包含检查

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

JQuery string contains check

javascriptjquerystringcomparisoncontains

提问by diggersworld

I need to check whether a string contains another string or not?

我需要检查一个字符串是否包含另一个字符串?

var str1 = "ABCDEFGHIJKLMNOP";
var str2 = "DEFG";

Which function do I use to find out if str1 contains str2?

我使用哪个函数来确定 str1 是否包含 str2?

回答by Rocket Hazmat

You can use javascript's indexOffunction.

您可以使用 javascript 的indexOf函数。

var str1 = "ABCDEFGHIJKLMNOP";
var str2 = "DEFG";
if(str1.indexOf(str2) != -1){
    console.log(str2 + " found");
}

回答by Khaihkd

var str1 = "ABCDEFGHIJKLMNOP";
var str2 = "DEFG";

sttr1.search(str2);

it will return the position of the match, or -1 if it isn't found.

它将返回匹配的位置,如果未找到则返回 -1。

回答by scott

Please try:

请尝试:

str1.contains(str2)

回答by eaglei22

I use,

我用,

var text = "some/String"; text.includes("/") <-- returns bool; true if "/" exists in string, false otherwise.

var text = "some/String"; text.includes("/") <-- returns bool; true if "/" exists in string, false otherwise.

回答by mzonerz

If you are worrying about Case sensitive change the case and compare the string.

如果您担心区分大小写,请更改大小写并比较字符串。

 if (stringvalue.toLocaleLowerCase().indexOf("mytexttocompare")!=-1)
        {

            alert("found");
        }