标签云

微信群

扫码加入我们

WeChat QR Code


It's easy with the indexOf method, you can see a tutorial of indexOf and substring here: dreamsyssoft.com/javascript-shell-scripting/…

2018年05月23日38分31秒

possible duplicate of JQuery string contains check

2018年05月23日38分31秒

you can see speed of r.indexOf(s) !== -1; fastest than others. hayageek.com/javascript-string-contains

2018年05月23日38分31秒

Here a benchmark for the most common ways to check if a string is in a string: jsben.ch/#/o6KmH

2018年05月23日38分31秒

Video covering the best of the options below in < 5 minutes, here: youtube.com/watch?v=KENPi0xTgcE

2018年05月23日38分31秒

Steve indexOf always returns a number so there’s no need to use !==. If you want to save bytes, you could use ~'foo'.indexOf('oo') which returns a truthy value if the substring is found, and a falsy value (0) if it isn’t.

2018年05月23日38分31秒

For the curious: in two's compliment systems, -1 is represented in binary as all 1s (1111 1111 1111 1111 1111 1111 1111 1111 for 32 bit). The bitwise inverse (~) of this is all zeros, or just zero, and therefore falsy. That's why the squiggle trick works, and it is pretty bad-ass if I must say so myself.

2018年05月23日38分31秒

SebNilsson You forgot to include the ~ operator that I suggested in my comment. ~'hello'.indexOf('h'); // -1, which is truthy, but ~'hello'.indexOf('x'); // 0, which is falsy.

2018年05月23日38分31秒

pramodc84 that link refers to the Array object indexOf method not to the String object method

2018年05月23日38分31秒

NicolasBarbulesco I am confident that all of the people who look at my code will know that [["\t\n 987654321e-400"]] === 0 is false. I am much less confident that everyone who looks at my code will know that [["\t\n 987654321e-432"]] == 0 is true.

2018年05月23日38分31秒

Don't modify objects you don't own. nczonline.net/blog/2010/03/02/…

2018年05月23日38分31秒

zachleat, that understandable in practice. But "foobar".contains("bar") would be a really useful exception to the rule.

2018年05月23日38分31秒

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.

2018年05月23日38分31秒

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

2018年05月23日38分31秒

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.

2018年05月23日38分31秒

JeremyW, 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.

2018年05月23日38分31秒

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

2018年05月23日38分31秒

Like this? String.prototype.contains = function (segment) { return this.indexOf(segment) !== -1; }; (BTW: Doing things on the prototype is bad)

2018年05月23日38分31秒

It is not support in chrome.....:(

2018年05月23日38分31秒

Norris It's in ES6. Load ES6 shim. You can use it now.

2018年05月23日38分31秒

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

2018年05月23日38分31秒

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.

2018年05月23日38分31秒

I haven't run a benchmark, but would str.toLowerCase().indexOf(searchstr.toLowerCase()) be much more efficient for case-insensitive search?

2018年05月23日38分31秒

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.

2018年05月23日38分31秒

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.

2018年05月23日38分31秒

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

2018年05月23日38分31秒

FWIW the linked MDN page has a simple shim/polyfill: developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…

2018年05月23日38分31秒

Yes, now I would rather recommend polyfill the ES6 standard includes() by following this: developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…

2018年05月23日38分31秒

it searches for the passed character or a word if it is found then search returns a integer value which is the position of word in the entire string. If a word or a character is not found then it search function returns -1.

2018年05月23日38分31秒

What's the advantage of !!~ over >-1?

2018年05月23日38分31秒

alex, There isn't any particular advantage other than not relying on magic numbers. Use what you feel comfortable with.

2018年05月24日38分31秒

zzzzBov !~~ is just as much relying on the magic number -1, and the fact that its bitwise representation is the complement of 0.

2018年05月23日38分31秒

!!~this.indexOf(arg); isn't easy understandable and not as clear in the context as it must be. It also relays on the fact ~-1 is 0, agreed with Martijn. Also it's slower than simple comparison with -1. But clearness is the main factor.

2018年05月23日38分31秒

Nick, I never claimed that it was a good way, I just said it was a common way. As far as clarity is concerned, I feel that it's a reasonable way to save a couple bytes for a library, but I tend to use foo.indexOf('bar') > -1

2018年05月23日38分31秒

support w3schools.com/jsref/jsref_endswith.asp

2018年05月23日38分31秒

That searches DOM elements though…

2018年05月23日38分31秒

dom parsing has nothing to do with the question

2018年05月23日38分31秒

it's loosely related... if the string you're searching through happens to be located within a DOM element, jQuery's :contains selector can be used.

2018年05月23日38分31秒

I don't see how figuring out the underscore method is in any way superior to simply using the well-documented core functionality provided in javascript, as illustrated here. To the type of coder that copies and pastes code, your sample code would be no more or less a "copy'n'paste code snippet" than any other solution provided here, except, it would require the addition of a library. Adding libraries simply to accomplish tasks that are just as easily done using the native language, regardless of library size, is bad advice. -1 from me for knee-jerk library use on a old question.

2018年05月23日38分31秒

If you are using Underscore already, you should probably use this approach anyway, as it makes your code more readable and more self-explanatory to people not that familiar with JavaScript... Remember that Stack Overflow answers are useful for more people than just the OP.

2018年05月24日38分31秒

_.str.include seems to be gone in underscore

2018年05月23日38分31秒

pixelearth It's not in underscore, but underscore.string. The link under include in the answer points to the description ;) If you use underscore currently, lodash might be a better solution anyway as it comes with its own includes method and even more very useful helper functions.

2018年05月23日38分31秒

Using a regex is a little overhead to only check for the presence of a substring.

2018年05月23日38分31秒

Benchmarks show otherwise; regex is more efficient in many cases, and more importantly, flexible enough to handle edge cases in a way that other solutions are not.

2018年05月23日38分31秒

Using regex usually results in 2 problems instead of one.

2018年05月23日38分31秒

If your string includes . or other regexp literals you will get false positives.

2018年05月24日38分31秒

This solutions breaks unless string is regex-escaped.

2018年05月23日38分31秒

Your first approach is not correct: elm.getAttribute("class") == elm.className != elm.getAttribute("className")

2018年05月23日38分31秒

if the string "test" includes a . or other regexp literals you will get false positives.

2018年05月23日38分31秒

stackoverflow.com/a/23598591/497418 and stackoverflow.com/a/12399125/497418 predate this answer, consider deleting it in favor of the later community wiki answer.

2018年05月23日38分31秒

Don’t modify objects you don’t own.

2018年05月23日38分31秒

-1; this question is about strings, not arrays.

2018年05月23日38分31秒

a string is an array of chars :)

2018年05月23日38分31秒

The sample HTML is not well formed - the body tag is missing.

2018年05月23日38分31秒

MikeMüller The question was why there is not a String.contains method, and the answer is that there is one in ES6. The link is provided merely as additional documentation.

2018年05月23日38分31秒

There was a contains in pre-release ES6 but it was changed to includes. Your contains method link redirects to the includes method here: developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… Here's the proof it was renamed: bugzilla.mozilla.org/show_bug.cgi?id=1102219

2018年05月23日38分31秒

I don't see any point in using lastIndexOf if you only want to check if a string contains a substring. search method is only for regular expressions. split method makes it only more complicated.

2018年05月23日38分31秒

ADS