首页 文章

如何检查字符串是否包含JavaScript中的子字符串?

提问于
浏览
7435

通常我会期待 String.contains() 方法,但似乎没有 .

检查这个的合理方法是什么?

30 回答

  • 20

    这段代码应该运行良好:

    var str="This is testing for javascript search !!!";
    if(str.search("for") != -1) {
       //logic
    }
    
  • 87
  • 18

    如上所述,您需要使用大写“O”调用indexOf . 还应该注意,在JavaScript类中是保留字,您需要使用className来获取此数据属性 . 它可能失败的原因是因为它返回一个空值 . 您可以执行以下操作来获取类值...

    var test = elm.getAttribute("className");
    //or
    var test = elm.className
    
  • 51

    你可以使用jQuery的 :contains 选择器 .

    $("div:contains('John')")
    

    在这里查看:contains-selector

  • 28

    由于这个问题非常受欢迎,我认为我可以为代码添加一些现代风格 .

    // const           : creates an immutable constant
    const allLinks   = document.getElementsByTagName("a");
    // [].reduce.call  : gives access to the reduce method on a HTMLCollection
    // () => {}        : ES6 arrow function
    const foundLinks = [].reduce.call(allLinks, (sum, link) => {
         // bitwise OR : converts the boolean value to a number
         return sum + (link.classList.contains("title") | 0);
    }, 0);
    
    // template literal
    console.log(`Found ${foundLinks || "no"} title class`);
    

    顺便说一句,正确答案是拼写错误 indexOf 或非标准 String.contains . 加载外部库(特别是如果代码是用纯JavaScript编写的)或搞乱 String.prototype 或使用regular expression有点矫枉过正 .

  • 57

    收集某种有效的解决方案:

    var stringVariable = "some text";
    var findString = "text";
    
    //using `indexOf()`
    var containResult1 = stringVariable.indexOf(findString) != -1;
    document.write(containResult1+', ');
    
    //using `lastIndexOf()`
    var containResult2 = stringVariable.lastIndexOf(findString) != -1;
    document.write(containResult2+', ');
    
    //using `search()`
    var containResult3 = stringVariable.search(findString) != -1;
    document.write(containResult3+', ');
         
    //using `split()`
    var containResult4 = stringVariable.split(findString)[0] != stringVariable;
    document.write(containResult4+'');
    
  • 13
    var index = haystack.indexOf(needle);
    
  • 125

    ES6 中,我们有一些调用 includes ,它完全符合你的要求:所以你可以这样做:

    'str1'.includes('str2');
    

    同样在 ES5 中,如果你广泛使用它,你可以简单地添加它:

    String.prototype.includes = String.prototype.includes || function(str) {
      return this.indexOf(str) > -1;
    }
    
  • 24

    JavaScript

    var str = "My big string contain apples and oranges";
     var n = str.indexOf("apples"); 
     alert(n); //will alert 22, -1 if not found
    

    jQuery

    <p>My big string contain apples and oranges</p>
      alert($("p:contains(apples)")[0] != undefined); //will alert true if found
    
  • 17

    A common way to write a contains method in JavaScript是:

    if (!String.prototype.contains) {
        String.prototype.contains = function (arg) {
            return !!~this.indexOf(arg);
        };
    }
    

    按位求反运算符( ~ )用于将 -1 转换为 0 (假),所有其他值将为非零(真值) .

    double boolean negation运算符用于将数字转换为布尔值 .

  • 81

    您可以使用以下语句轻松地将 contains 方法添加到String:

    String.prototype.contains = function(it) { return this.indexOf(it) != -1; };
    

    注意:请参阅以下注释,了解不使用此参数的有效参数 . 我的建议:用你自己的判断 .

    或者:

    if (typeof String.prototype.contains === 'undefined') { String.prototype.contains = function(it) { return this.indexOf(it) != -1; }; }
    
  • 24

    您的代码存在的问题是JavaScript区分大小写 . 你的方法调用

    indexof()
    

    应该是

    indexOf()
    

    尝试修复它,看看是否有帮助:

    if (test.indexOf("title") !=-1) {
        alert(elm);
        foundLinks++;
    }
    
  • 25

    您正在寻找 .indexOf MDN .

    indexOf 将返回匹配的子字符串的索引 . 索引将与子字符串的开始位置相关联 . 如果没有匹配,则返回-1 . 这是一个 simple demo 的概念:

    var str = "Hello World"; // For example, lets search this string,
    var term = "World"; // for the term "World",
    var index = str.indexOf(term); // and get its index.
    if (index != -1) { // If the index is not -1 then the term was matched in the string,
      alert(index); // and we can do some work based on that logic. (6 is alerted)
    }
    
  • 29

    在数组中使用 contains 方法的JavaScript代码:

    <html>
        <head>
            <h2>Use of contains() method</h2>
            <script>
                Array.prototype.contains = function (element) {
                    for (var i = 0; i < this.length; i++) {
                        if (this[i] == element) {
                            return true;
                        }
                    }
                    return false;
                }
                arr1 = ["Rose", "India", "Technologies"];
                document.write("The condition is "+arr1.contains("India")+"<br>");
            </script>
        </head>
    
        <b>[If the specified element is present in the array, it returns true otherwise
        returns false.]</b>
    
    </html>
    

    在给定的代码中, contains 方法确定指定的元素是否存在于数组中 . 如果指定的元素存在于数组中,则返回true,否则返回false .

  • 14

    这对我有用 . 它选择不包含术语“已删除:”的字符串

    if (eventString.indexOf("Deleted:") == -1)
    
  • 70

    String.prototype.includes()在ES6中引入 .

    确定是否可以在另一个字符串中找到一个字符串,并根据需要返回true或false .

    语法

    var contained = str.includes(searchString [, position]);
    

    参数

    searchString
    

    要在此字符串中搜索的字符串 .

    position
    

    此字符串中开始搜索 searchString 的位置默认为0 .

    示例

    var str = "To be, or not to be, that is the question.";
    
    console.log(str.includes("To be"));    // true
    console.log(str.includes("question")); // true
    console.log(str.includes("To be", 1)); // false
    

    注意

    这可能需要旧版浏览器中的ES6垫片 .

  • 12007

    使用正则表达式:

    RegExp.test(string)

  • 852

    使用内置的和最简单的一个,即字符串上的 match() . 要实现您期待的目标,请执行以下操作:

    var stringData ="anyString Data";
    
    var subStringToSearch = "any";
    
    // This will give back the substring if matches and if not returns null
    var doesContains = stringData.match(subStringToSearch);
    
    if(doesContains !=null) {
        alert("Contains Substring");
    }
    
  • 171

    有一种更流畅,更好的方法,它使用(BitWise NOT)运算符 .

    if(~"John".indexOf("J")) {
      alert("Found")
    }
    else {
      alert("Not Found");
    }
    

    按位不将“x”转换为 - (x 1)所以,如果x从indexOf方法变为-1,那么它将被转换为 - (-1 1)= -0这是一个假值 .

  • 52

    您可以使用JavaScript search() 方法 .

    语法是: string.search(regexp)

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

    见那里的例子:jsref_search

    您不需要复杂的正则表达式语法 . 如果你不熟悉它们,那么简单的_83544就可以了 . 如果您希望测试不区分大小写,那么您应该 st.search(/title/i) .

  • 51

    由于存在关于使用原型的抱怨,并且因为使用 indexOf 会使您的代码不易读取,并且因为正则表达式是过度的:

    function stringContains(inputString, stringToFind) {
        return (inputString.indexOf(stringToFind) != -1);
    }
    

    这就是我最终要做的妥协 .

  • 36

    简单的解决方法

    if (!String.prototype.contains) {
      String.prototype.contains= function() {
        return String.prototype.indexOf.apply(this, arguments) !== -1;
      };
    }
    

    你可以用以下方式使用

    "hello".contains("he") // true
    "hello world".contains("lo w")//true
    "hello world".contains("lo wa")//false
    "hello world".contains(" ")//true
    "hello world".contains("  ")//false
    

    MDN reference

  • 395

    String.prototype.indexOf()或String.prototype.search()?!

    正如其他人已经提到的,JavaScript字符串同时具有indexOfsearch方法 .

    两者之间的关键区别在于 indexOf 仅用于普通子串,而 search 也支持正则表达式 . 当然,使用 indexOf 的好处是它更快 .

    另见In JavaScript, what is the difference between indexOf() and search()? .

    实现自己的String.prototype.contains()方法

    如果你想为每个字符串添加你自己的 contains 方法,最好的方法是@zzzzBov的方法:

    if (!String.prototype.contains) {
        String.prototype.contains = function (arg) {
            return !!~this.indexOf(arg);
        };
    }
    

    你会像这样使用它:

    'Hello World'.contains('orl');
    

    实现自定义实用程序库

    通常不赞成将自己的自定义方法添加到标准对象中例如,JavaScript,因为它可能会破坏兼容性 .

    如果您真的需要自己的 contains 方法和/或其他自定义字符串方法,最好创建自己的实用程序库并将自定义字符串方法添加到该库:

    var helper = {};
    
    helper.string = {
        contains : function (haystack, needle) {
            return !!~haystack.indexOf(needle);
        },
        ...
    };
    

    你会像这样使用它:

    helper.string.contains('Hello World', 'orl');
    

    使用第三方实用程序库

    如果您不想创建自己的自定义帮助程序库,当然 - 始终可以选择使用第三方实用程序库 . 如@nachtigall所述,最受欢迎的是LodashUnderscore.js .

    在Lodash中,你可以使用 _.includes() ,你可以这样使用:

    _.includes('Hello World', 'orl');
    

    在Underscore.js中,你可以使用 _.str.include() ,你可以这样使用:

    _.str.include('Hello World', 'orl');
    
  • 67

    var a  = "Test String";
    
    if(a.search("ring")!=-1){
         //exist 
    } else {
         //not found 
    }
    
  • 83

    ES5

    var s = "foo";
    alert(s.indexOf("oo") > -1);
    

    ES6 中有三种新方法: includes()startsWith()endsWith() .

    var msg = "Hello world!";
    
    console.log(msg.startsWith("Hello"));       // true
    console.log(msg.endsWith("!"));             // true
    console.log(msg.includes("o"));             // true
    
    console.log(msg.startsWith("o", 4));        // true
    console.log(msg.endsWith("o", 8));          // true
    console.log(msg.includes("o", 8));          // false
    
  • 353

    以下列出了当前的可能性:

    1. (ES6) includes - go to answer

    var string = "foo",
        substring = "oo";
    string.includes(substring);
    

    2. ES5 and older indexOf

    var string = "foo",
        substring = "oo";
    string.indexOf(substring) !== -1;
    

    String.prototype.indexOf返回另一个字符串中字符串的位置 . 如果未找到,则返回 -1 .

    3. search - go to answer

    var string = "foo",
        expr = /oo/;
    string.search(expr);
    

    4. lodash includes - go to answer

    var string = "foo",
        substring = "oo";
    _.includes(string, substring);
    

    5. RegExp - go to answer

    var string = "foo",
        expr = /oo/;  // no quotes here
    expr.test(string);
    

    6. Match - go to answer

    var string = "foo",
        expr = /oo/;
    string.match(expr);
    

    Performance tests显示 indexOf 可能是最佳选择,如果涉及到速度问题的那一点 .

  • 448

    您可以使用经过充分测试和记录的库,而不是使用网络上此处和此处找到的代码段 . 我建议的两个选项:


    1st option: 使用Lodash:它有一个includes方法:

    _.includes('foobar', 'ob');
    // → true
    

    Lodash是npm最受欢迎的javascript库依赖项,并且有大量方便的javascript实用程序方法 . 因此,对于许多项目,无论如何你都会想要这个;-)


    2nd option: 或者使用Underscore.string:它有一个include方法:

    _.str.include('foobar', 'ob');
    // → true
    

    以下是Underscore.string的描述,它只增加了9kb,但为您提供了经过充分测试和记录的库具有over copy'n'paste代码片段的所有优点:

    Underscore.string是用于使用字符串进行舒适操作的JavaScript库,受Prototype.js,Right.js,Underscore和漂亮的Ruby语言启发的Underscore.js的扩展 . Underscore.string为您提供了几个有用的函数:capitalize,clean,includes,count,escapeHTML,unescapeHTML,insert,splice,startsWith,endsWith,titleize,trim,truncate等 .

    请注意,Underscore.string受Underscore.js的影响但可以在没有它的情况下使用 .


    Last not Least: 使用JavaScript版本ES6内置includes方法:

    'foobar'.includes('ob');
    // → true
    

    大多数现代浏览器已经支持它,关注ES6 compatibility table .

  • 244

    There is a string.includes in ES6

    "potato".includes("to");
    > true
    

    请注意,您可能需要加载 es6-shim 或类似内容才能在旧版浏览器上使用它 .

    require('es6-shim')
    
  • 63

    这样做的另一个选择是:

    您可以使用匹配功能,即:

    x = "teststring";
    
    if (x.match("test")) {
         // Code
    }
    

    match()也可以使用正则表达式:

    x = "teststring";
    
    if (x.match(/test/i)) {
         // Code
    }
    
  • 21

    如果你正在寻找一种替代方法来编写丑陋的-1检查,那么你可以先添加一个〜代替 .

    if (~haystack.indexOf('needle')) alert('found');
    

    Joe Zimmerman - 您将看到使用~on -1将其转换为0.数字0是一个假值,这意味着它在转换为布尔值时将计算为false . 这可能看起来不像是一个很大的洞察力,但是当找不到查询时,记住像indexOf这样的函数将返回-1 . 这意味着不要写类似的东西:if(someStr.indexOf(“a”)> = 0){
    // 找到了
    } else {
    // 未找到
    }
    您现在可以在代码中使用更少的字符,因此您可以这样写:if(~someStr.indexOf(“a”)){
    // 找到了
    } else {
    // 未找到
    }

    更多details here

相关问题