niomsi.blogg.se

Javascript string includes
Javascript string includes











javascript string includes

Just like the includes() method, the indexOf() method is case sensitive and also supports the offset parameter: > let str = 'StackAbuse' Here's an example: > let str = 'stackabuse' Īs you can see, this method returns the 0-based index position of the substring, and a -1 when the substring wasn't found. Instead of returning a boolean value indicating the presence of the substring, it actually returns the index location of the substring, or -1 if it isn't present. The String.indexOf() method is much like the previous includes() method (and it's suitable to be used in a polyfill for includes() as well), but the only difference is the return value. So if you know that the substring isn't contained in the first 50 characters (or you just don't want it to match those characters), then you can use the method like this: str.includes(substr, 50) Īn offset of below 0 just starts the search from index 0, and an offset greater than string.length returns false since the search starts from string.length. A second argument can be provided that tells the method at which index to start the search. While this is enough for most use-cases, the includes() method also provides another option that may be useful to you. This is a case sensitive search, so the following will not match the substring: > let str = 'StackAbuse' It works like this: > let str = 'stackabuse' Īs you can see, a boolean value is returned since the string "stack" is a substring of "stackabuse". If all you need to do is get a boolean value indicating if the substring is in another string, then this is what you'll want to use.

javascript string includes

This method was introduced in ES6 and is typically the preferred method for simple use-cases. Keep this in mind when reading the article as it'll likely help you for similar use-cases. Note: The first two methods shown below also works on arrays, which tells you if an array contains a given value (or the index of it for indexOf()).













Javascript string includes