如何检查一个字符串是否包含子字符串在 JavaScript 中?

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

What is a reasonable way to check for this?

转载于:https://stackoverflow.com/questions/1789945/how-to-check-whether-a-string-contains-a-substring-in-javascript

weixin_41568183
零零乙 TypeScript incorporate string.container actually
2 年多之前 回复
csdnceshi68
local-host developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
接近 3 年之前 回复
csdnceshi58
Didn"t forge A very useful and widely used website is W3Schools, see w3schools.com/jsref/default.asp - "This section contains a complete JavaScript reference documentation."
接近 3 年之前 回复
csdnceshi67
bug^君 Video covering the best of the options below in < 5 minutes, here: youtube.com/watch?v=KENPi0xTgcE
3 年多之前 回复
csdnceshi63
elliott.david Here a benchmark for the most common ways to check if a string is in a string: jsben.ch/#/o6KmH
接近 4 年之前 回复
csdnceshi69
YaoRaoLov Finally! There is an includes() method for strings in ECMA6. Supported by everyone except IE. A good polyfill is available in Mozilla's docs: developer.mozilla.org/en/docs/Web/JavaScript/Reference/…
接近 4 年之前 回复
weixin_41568196
撒拉嘿哟木头 you can try this "foo bar".match('oo') ? console.log("contained") : console.log("not contained");
大约 4 年之前 回复
csdnceshi75
衫裤跑路 you can see speed of r.indexOf(s) !== -1; fastest than others. hayageek.com/javascript-string-contains
接近 5 年之前 回复
csdnceshi61
derek5. possible duplicate of JQuery string contains check
接近 5 年之前 回复
csdnceshi73
喵-见缝插针 It's easy with the indexOf method, you can see a tutorial of indexOf and substring here: dreamsyssoft.com/javascript-shell-scripting/…
5 年多之前 回复

29个回答

Here is a list of current possibilities:

1. (ES6) includesgo 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 returns the position of the string in the other string. If not found, it will return -1.

3. searchgo to answer

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

4. lodash includesgo to answer

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

5. RegExpgo to answer

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

6. Matchgo to answer

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.

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

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:

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

weixin_41568110
七度&光 Yes, now I would rather recommend polyfill the ES6 standard includes() by following this: developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
接近 4 年之前 回复

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

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; }; }
csdnceshi59
ℙℕℤℝ Don't monkey patch browser objects.
大约 2 年之前 回复
csdnceshi61
derek5. It's no the best practice to modify such objects..
3 年多之前 回复
csdnceshi60
℡Wang Yan ECMAScript 6 removed .contains because of invalid polyfills. It now contains .includes instead.
5 年多之前 回复
csdnceshi69
YaoRaoLov There is absolutely nothing wrong with polyfilling the standards track .contains implementation with a typeof guard. It should simply be changed to String.prototype.indexOf.apply(this, arguments) !== -1
接近 6 年之前 回复
weixin_41568184
叼花硬汉 != vs !== anyone?
接近 6 年之前 回复
csdnceshi52
妄徒之命 -100 if I could. Don't do this. Ever. Others have explained some of the why. But a general principle is that if you make objects that LOOK like they're something else; someone will think they ARE something else. This is how to end up with a maintenance nightmare. Don't do this. Ever.
接近 6 年之前 回复
csdnceshi63
elliott.david JSHint warns about overwriting prototypes of native objects.
大约 6 年之前 回复
weixin_41568208
北城已荒凉 ECMAScript 6 includes String.prototype.contains wiki.ecmascript.org/doku.php?id=harmony:string_extras
接近 7 年之前 回复
csdnceshi79
python小菜 The problem is the method here isn't compatible with the built-in method. Any code that assumes the built-in method semantics will be exposed (ads on the page, WordPress plugins, anything else), will get this, and will get nonsense behavior. See bugzilla.mozilla.org/show_bug.cgi?id=789036 for a list of a bunch of sites that broke because MooTools 1.2.x implemented an incompatible String.prototype.contains (presumably by only conditionally patching, if there was no existing contains method), and the browser-provided version didn't behave like elements of the page expected.
接近 7 年之前 回复
csdnceshi51
旧行李 I'm curious: what causes the breakage?
接近 7 年之前 回复
csdnceshi79
python小菜 Note that a String.prototype.contains method is in the process of being standardized, making this modification an even worse idea than it was when first answered. And it is precisely these sorts of modifications, made by unthinking web developers, that are making it such a pain to ship this new method in Firefox. (It's implemented in the latest nightly builds, and I think in Aurora builds. But it's unknown when it'll make it into a release, as there has been site breakage from the addition that must be laboriously resolved first.)
接近 8 年之前 回复
weixin_41568134
MAO-EYE if (typeof String.prototype.contains === 'undefined') { String.prototype.contains = function(it) { return this.indexOf(it) != -1; }; } else { alert ("Your code may now be broken! Check the definition of String.prototype.contains."); }
大约 8 年之前 回复
csdnceshi80
胖鸭 If you document your modifications and share them with the team then it's fine. It's simply a matter of discipline. If your team doesn't follow documentation then you'll have bigger issues.
接近 9 年之前 回复
csdnceshi67
bug^君 I this it is preferrable to use this function if you are going to be using this kind of indexOf's frequently. @zachleat, I would disagree that using indexOf is more readable than contains. Contains describes what is happening, where to some indexOf() != -1 may not be so transparent. But to each their own, as long as you're consistant.
大约 9 年之前 回复
csdnceshi78
程序go if (typeof String.prototype.contains === 'undefined') { String.prototype.contains = function(it) { return this.indexOf(it) != -1; }; }
大约 9 年之前 回复
csdnceshi68
local-host I agree with @Zachleat. This is a cool concept, but I also think it's important to write code that will be understandable long after you're gone. ("contains" is easy to understand, but it's easy to get carried away and write your own language in JavaScript. It's great as a Computer Science exercise but horrible in a production environment).
9 年多之前 回复
csdnceshi66
必承其重 | 欲带皇冠 Eh, my preference would be to adapt my mental model to fit JavaScript and just use indexOf. It will make the code easier to understand for the next JavaScripter that comes along and has to read it.
9 年多之前 回复
csdnceshi74
7*4 that understandable in practice. But "foobar".contains("bar") would be a really useful exception to the rule.
9 年多之前 回复
weixin_41568174
from.. I agree that that's a best practice in general, but I feel that it's generally OK for app-specific code. It'd be terrible for a library though.
9 年多之前 回复
csdnceshi66
必承其重 | 欲带皇冠 Don't modify objects you don't own. nczonline.net/blog/2010/03/02/…
9 年多之前 回复

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

indexof()

should actually be

indexOf()

Try fixing it and see if that helps:

if (test.indexOf("title") !=-1) {
    alert(elm);
    foundLinks++;
}
csdnceshi77
狐狸.fox I would say at this point the value of this answer is that people that have made this exact same mistake (indexof instead of indexOf) can find this answer and see what's going on. I wouldn't touch the question any more.
5 年多之前 回复
var index = haystack.indexOf(needle);

You could use the JavaScript search() method.

Syntax is: string.search(regexp)

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

See examples there: 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).

csdnceshi71
Memor.の .search() is for regular expressions. For strings it's better to use .indexOf().
4 年多之前 回复
csdnceshi61
derek5. You can use an escapeRegExp function to make the serach text safe. function escapeRegExp(string){ return string.replace(/([.*+?^=!:${}()|\[\]\/\\])/g, "\\$1"); } from developer.mozilla.org/en/docs/Web/JavaScript/Guide/…
大约 6 年之前 回复
weixin_41568184
叼花硬汉 Search can lead to bugs. As misaxi said, you then have to escape some characters. I was using search not realizing that the parameter expected a regex, and was searching for the pipe character. As it turns out, any string .search('|') == 0.
6 年多之前 回复
csdnceshi76
斗士狗 With a benchmark and it turns out search is more efficient for case insensitive searching. jsperf.com/string-compare-perf-test But it could be tricky to use regex search as you need to escape some characters.
大约 7 年之前 回复
csdnceshi67
bug^君 I haven't run a benchmark, but would str.toLowerCase().indexOf(searchstr.toLowerCase()) be much more efficient for case-insensitive search?
8 年多之前 回复
csdnceshi70
笑故挽风 This seems like it would be slower than the indexOf function because it would have to parse the RegEx. However, if you want something case insensitive, your way would be the way to go (I think), although that was not what was asked. Even though it wasn't asked, I'm voting this up just because of the case insensitive option.
大约 10 年之前 回复

There is a string.includes in ES6:

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

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

require('es6-shim')
csdnceshi71
Memor.の Is there a way to make the function case-insensitive? If not, curious as to which is faster: search() using regex with the case insensitivity modifier or toLowerCase() with includes().
2 年多之前 回复
csdnceshi77
狐狸.fox Dont use includes it`ll break in IE11. Learn the hard way.
接近 4 年之前 回复
weixin_41568184
叼花硬汉 The recommended Polyfill is: developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… if (!String.prototype.includes) { String.prototype.includes = function(search, start) { 'use strict'; if (typeof start !== 'number') { start = 0; } if (start + search.length > this.length) { return false; } else { return this.indexOf(search, start) !== -1; } }; }
大约 4 年之前 回复
weixin_41568196
撒拉嘿哟木头 latest chrome supports this method, but IE10 doesn't. Be aware of using it
4 年多之前 回复
csdnceshi78
程序go you can use includes() if you are pre-compiling from ES6 to ES5 using babel
大约 5 年之前 回复
csdnceshi73
喵-见缝插针 .contains() and .includes() are both experimental, re: non-standard. I would not recommend their use in production systems. I'd stick with .indexOf() for now.
5 年多之前 回复
csdnceshi72
谁还没个明天 It's in ES6. Load ES6 shim. You can use it now.
5 年多之前 回复
csdnceshi74
7*4 That's lightyears ahead of us. Only an ES7 proposal. Still - a nice heads up, and I hope the day comes soon when we can safely use it :).
5 年多之前 回复
csdnceshi54
hurriedly% It is not support in chrome.....:(
大约 6 年之前 回复
csdnceshi64
游.程 Like this? String.prototype.contains = function (segment) { return this.indexOf(segment) !== -1; }; (BTW: Doing things on the prototype is bad)
7 年多之前 回复
weixin_41568127
?yb? because I was used to "contains" in other languages and just implemented my feature with it, I just ran into the error. So, short feedback about the support. Firefox 19 - OSX => OK, Firefox 19 - Windows => NOK, Chrome - OSX,Windows => NOK
7 年多之前 回复

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

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

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.

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.

</div>
csdnceshi75
衫裤跑路 FWIW the linked MDN page has a simple shim/polyfill: developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
接近 4 年之前 回复

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.

Example

var a  = "Test String";

if(a.search("ring")!=-1){
     //exist 
} else {
     //not found 
}
共29条数据 1 3 尾页
Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问