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

[英]How to check whether a string contains a substring in JavaScript?


Usually I would expect a String.contains() method, but there doesn't seem to be one.

通常我希望使用String.contains()方法,但似乎没有。

What is a reasonable way to check for this?

什么是合理的检查方法?

49 个解决方案

#1


11276  

Here is a list of current possibilities:

以下是当前的可能性清单:

1. (ES6) includesgo to answer

1。(ES6)includes-go回答

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

2. ES5 and older indexOf

2。ES5以上indexOf

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

String.prototype.indexOf returns the position of the string in the other string. If not found, it will return -1.

String.prototype。indexOf返回字符串在另一个字符串中的位置。如果没有找到,它将返回-1。

3. searchgo to answer

3所示。搜索答案

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

4. lodash includesgo to answer

4所示。lodash includes-go回答

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

5. RegExpgo to answer

5。RegExp-go回答

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

6. Matchgo to answer

6。比赛来回答

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

Performance tests are showing that indexOf might be the best choice, if it comes to a point where speed matters.

性能测试显示,如果涉及到速度问题,indexOf可能是最佳选择。

#2


808  

You can easily add a contains method to String with this statement:

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

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

Note: see the comments below for a valid argument for not using this. My advice: use your own judgement.

注意:请参阅下面的注释,以获得不使用此参数的有效参数。我的建议是:用你自己的判断。

Alternatively:

另外:

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

#3


418  

The problem with your code is that JavaScript is case sensitive. Your method call

代码的问题在于JavaScript是区分大小写的。你的方法调用

indexof()

should actually be

实际上应该

indexOf()

Try fixing it and see if that helps:

试着修复它,看看是否有用:

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

#4


338  

There is a string.includes in ES6:

这是一个字符串。包括在ES6:

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

Note you may need to load es6-shim or similar to get this working on older browsers.

注意,您可能需要加载es6-shim或类似的文件,以便在旧的浏览器上运行。

require('es6-shim')

#5


333  

var index = haystack.indexOf(needle);

#6


233  

You could use the JavaScript search() method.

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

Syntax is: string.search(regexp)

语法:string.search(正则表达式)

It returns the position of the match, or -1 if no match is found.

它返回匹配项的位置,如果没有找到匹配项,返回-1。

See examples there: jsref_search

看到的例子:jsref_search

You don't need a complicated regular expression syntax. If you are not familiar with them a simple st.search("title") will do. If you want your test to be case insensitive, then you should do st.search(/title/i).

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

#7


166  

String.prototype.includes() was introduced in ES6.

在ES6中引入了include()。

Determines whether one string may be found within another string, returning true or false as appropriate.

确定是否在另一个字符串中找到一个字符串,返回true或false。

Syntax

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

Parameters

searchString

A string to be searched for within this string.

在这个字符串中要搜索的字符串。

position

The position in this string at which to begin searching for searchString defaults to 0.

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

Example

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  

Note

This may require ES6 shim in older browsers.

这可能需要在旧浏览器中使用ES6 shim。

#8


119  

If you were looking for an alternative to write the ugly -1 check, you prepend a ~ tilde instead.

如果您正在寻找一种替代方法来编写丑陋的-1检查,那么您应该在~ tilde之前。

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

Joe Zimmerman - you'll see that using ~ on -1 converts it to 0. The number 0 is a falsey value, meaning that it will evaluate to false when converted to a Boolean. That might not seem like a big insight at first, but remember functions like indexOf will return -1 when the query is not found. This means that instead of writing something similar to this:

Joe Zimmerman -你会看到使用~ on -1将它转换为0。数字0是一个falsey值,这意味着当它被转换成布尔值时,它的值为false。乍一看,这似乎不是一个大的见解,但请记住,当查询未找到时,indexOf等函数将返回-1。这意味着,不要写类似的东西:

if (someStr.indexOf("a") >= 0) {
  // Found it
} else  {
  // Not Found
}

You can now have fewer characters in your code so you can write it like this:

现在你的代码中可以少写一些字符,所以你可以这样写:

if (~someStr.indexOf("a")) {
  // Found it
} else  {
  // Not Found
}

More details here

更多细节在这里

#9


82  

This piece of code should work well:

这段代码应该运行良好:

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

#10


77  

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

在JavaScript中编写包含方法的常用方法是:

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

The bitwise negation operator (~) is used to turn -1 into 0 (falsey), and all other values will be non-zero (truthy).

位否定运算符(~)用于将-1变为0 (falsey),所有其他值都是非零的(truthy)。

The double boolean negation operators are used to cast the number into a boolean.

双布尔否定运算符用于将数字转换成布尔值。

#11


76  

In ES5

在ES5

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

In ES6 there are three new methods: includes(), startsWith(), endsWith().

在ES6中有三种新方法:include()、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

#12


63  

You can use jQuery's :contains selector.

您可以使用jQuery的:包含选择器。

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

Check it here: contains-selector

在这里检查:contains-selector

#13


63  

Instead of using code snippets found here and there on the web, you can also use a well-tested and documented library. Two Options I would recommend:

您还可以使用经过良好测试和文档化的库,而不是使用在web上找到的代码片段。我建议两种选择:


1st option: Use Lodash: It has an includes method:

第一个选项:使用Lodash:它有一个include方法:

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

Lodash is the most popular javascript library dependency for npm and has loads of handy javascript utility methods. So for many projects you would want this anyway ;-)

Lodash是npm最流行的javascript库依赖项,它有大量方便的javascript实用程序方法。所以对于很多项目你都想要这个;-)


2nd option: Or use Underscore.string: It has an include method:

第二种选择:或使用下划线。字符串:它有一个include方法:

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

Here is the description of Underscore.string, it just adds 9kb but gives you all the advantages a well-tested and documented library has over copy'n'paste code snippets:

下面是下划线的描述。字符串,它只增加了9kb,但是与复制'n'paste代码片段相比,经过良好测试和文档化的库具有的所有优势:

Underscore.string is JavaScript library for comfortable manipulation with strings, extension for Underscore.js inspired by Prototype.js, Right.js, Underscore and beautiful Ruby language.

下划线。string是JavaScript库,用于使用字符串进行轻松操作,下划线扩展。js灵感来自原型。js。下划线和漂亮的Ruby语言。

Underscore.string provides you several useful functions: capitalize, clean, includes, count, escapeHTML, unescapeHTML, insert, splice, startsWith, endsWith, titleize, trim, truncate and so on.

下划线。string提供了几个有用的函数:大写、清除、包含、计数、escapeHTML、unescapeHTML、insert、splice、startsWith、endsWith、titleize、trim、truncatetable、trunehtml等。

Note well, Underscore.string is influenced by Underscore.js but can be used without it.

注意下划线。字符串受下划线的影响。但是可以不使用它。


Last not Least: With JavaScript version ES6 comes an built-in includes method:

最后一点:使用JavaScript版本ES6,内置的include方法:

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

Most modern browsers already support it, have an eye on the ES6 compatibility table.

大多数现代浏览器已经支持它了,关注ES6兼容性表。

#14


58  

Use a regular expression:

使用一个正则表达式:

RegExp.test(string)

RegExp.test(字符串)

#15


48  

This just worked for me. It selects for strings that do not contain the term "Deleted:"

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

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

#16


48  

You were looking for .indexOfMDN.

你在找。indexofmdn。

indexOf is going to return an index to the matched substring. The index will correlate to where the substring starts. If there is no match, a -1 is returned. Here is a simple demo of that concept:

indexOf将返回一个索引到匹配的子字符串。索引将与子字符串开始的位置相关联。如果没有匹配,则返回-1。下面是这个概念的一个简单演示:

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)
}

#17


48  

Another option of doing this is:

另一个选择是:

You can use the match function, that is, something like:

可以使用match函数,即:

x = "teststring";

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

match() can also work with regular expression :

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

x = "teststring";

if (x.match(/test/i)) {
     // Code
}

#18


47  

You need to call indexOf with a capital "O" as mentioned. It should also be noted, that in JavaScript class is a reserved word, you need to use className to get this data attribute. The reason it's probably failing is because it's returning a null value. You can do the following to get your class value...

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

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

#19


33  

Since the question is pretty popular, I thought I could add a little modern flavor to the code.

由于这个问题很受欢迎,我想我可以在代码中加入一点现代气息。

// 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`);

BTW, the correct answer is misspelling indexOf or the non-standard String.contains. Loading an external library (especially if the code is written in pure JavaScript) or messing with String.prototype or using a regular expression is a little overkill.

顺便说一句,正确的答案是拼写错误索引或非标准字符串。加载外部库(特别是如果代码是用纯JavaScript编写的)或使用字符串。原型或使用正则表达式有点过分。

#20


26  

There is a sleek and better way to do this and it is using the (BitWise NOT) operator.

有一种圆滑而更好的方法,它使用的是(位不)操作符。

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

The Bitwise Not converts "x" into -(x + 1) so, if the x turns out -1 from indexOf method.then it will be converted into -( -1 + 1) = -0 which is a falsy value .

按位计算,不会将“x”转换成-(x + 1)所以,如果从indexOf方法中得到-1。然后将它转换为-(-1 + 1)= -0,这是一个伪值。

#21


23  

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

As others have already mentioned, JavaScript strings have both an indexOf and search method.

正如其他人已经提到的,JavaScript字符串有索引和搜索方法。

The key difference between both, is that indexOf is for plain substrings only, whereas search also supports regular expressions. Of course, an upside of using indexOf is that it's faster.

关键区别是indexOf仅供纯子字符串,而搜索引擎也支持正则表达式。当然,使用indexOf的一个好处是它的速度更快。

See also In JavaScript, what is the difference between indexOf() and search()?.

在JavaScript中也可以看到,indexOf()和search()之间的区别是什么?

Implementing your own String.prototype.contains() method

If you want to add your own contains method to every string, the best way to do it would be @zzzzBov's approach:

如果你想添加自己的每一个字符串包含方法,最好的方法就是@zzzzBov的方法:

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

You would use it like this:

你可以这样使用:

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

Implementing a custom utility library

It is generally frowned upon to add your own custom methods to standard objects in JavaScript, for example, because it might break forward compatibility.

通常,在JavaScript中添加自己的自定义方法到标准对象中是不可取的,因为它可能会破坏兼容性。

If you really want your own contains method and/or other custom string methods, it's better to create your own utility library and add your custom string methods to that library:

如果您确实想要自己的包含方法和/或其他自定义字符串方法,那么最好创建自己的实用程序库,并将自定义字符串方法添加到该库中:

var helper = {};

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

You would use it like this:

你可以这样使用:

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

Using a third-party utility library

If you don't want to create your own custom helper library, there is - of course - always the option of using a third-party utility library. As mentioned by @nachtigall, the most popular ones are Lodash and Underscore.js.

如果您不想创建自己的自定义帮助程序库,当然,总是可以选择使用第三方实用程序库。@nachtigall提到过,最流行的是Lodash和Underscore.js。

In Lodash, you could use _.includes(), which you use like this:

在Lodash中,可以使用_.include(),您可以这样使用:

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

In Underscore.js, you could use _.str.include(), which you use like this :

在强调。js,您可以使用_.str.include(),它使用这样的:

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

#22


22  

Simple workaround

简单的解决方法

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

you can use in the following way

您可以使用以下方式

"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

MDN参考

#23


21  

Example

例子

var a  = "Test String";

if(a.search("ring")!=-1){
     //exist 
} else {
     //not found 
}

#24


20  

JavaScript code to use the contains method in an array:

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

<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>

In the given code the contains method determines whether the specified element is present in the array or not. If the specified element is present in the array, it returns true, otherwise it returns false.

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

#25


20  

ES6 contains String.prototype.includes.

ES6包含String.prototype.includes。

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/includes

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/includes

#26


18  

To collect some kind of valid solutions:

收集一些有效的解决方案:

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+'');

#27


16  

Since there is a complaint about using the prototype, and since using indexOf makes your code less readable, and since regexp is overkill:

因为有关于使用原型的抱怨,而且使用indexOf会使您的代码可读性降低,而且由于regexp是过量的:

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

That is the compromise I ended up going for.

这就是我最后的妥协。

#28


16  

JavaScript

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

jQuery

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

#29


12  

Use the inbuilt and simplest one i.e match() on the string. To achieve what you are looking forward do this:

使用内置的和简单的我。e()相匹配的字符串。达到你所期待这样做:

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");
}

#30


12  

The easyest way is indeed using indexOf. To just check a string string for a substring substr you can use this method:

最简单的方法是使用indexOf。只是检查字符串的子串的子串字符串可以使用这个方法:

string = "asdf";
substr = "as";
alert(string.indexOf(substr) == -1 ? false : true);

As you wanted the function string.contains(), you can implement it yourself like this:

如您希望函数string.contains(),您可以自己实现它:

String.prototype.contains = function(test) {
    return this.indexOf(test) == -1 ? false : true;
};

Now you can use this ecen shorter method to check if a string contains a special substring:

现在您可以使用这个ecen更短的方法来检查一个字符串是否包含一个特殊的子字符串:

string = "asdf";
alert(string.contains("as"));

Here is a JSFiddle as well.

这是一个JSFiddle。

智能推荐

注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:http://www.silva-art.net/blog/2018/03/21/39ca04e5ffe143e271fbeb3c0b76e129.html



 
© 2014-2019 ITdaan.com 粤ICP备14056181号  

赞助商广告