- How to check if a string “StartsWith” another string?
- We can use ECMAScript 6’s String.prototype.startsWith() method, but it’s not yet supported in all browsers.
- We want to use a shim/polyfill to add it on browsers that don’t support it.
if we need shim, use either:
- String.prototype.startsWith shim, or
- The es6-shim, which shims as much of the ES6 spec as possible, including String.prototype.startsWith
We can use the following:
- To Use stringObject.substring
- Another alternative with .lastIndexOf:
- This looks backwards through haystack for an occurrence of needle starting from index 0 of haystack. In other words, it only checks if haystack starts with needle.
- In principle, this should have performance advantages over some other approaches:
- It doesn’t search the entire haystack.
- It doesn’t create a new temporary string and then immediately discard it.
- using regex’s .test method:
To do this with a dynamic string rather than a hardcoded one (assuming that the string will not contain any regexp control characters):
- Here is an another way of solution:
- Checking whether the function already exists in case a future browser implements it in native code or if it is implemented by another library.
- For example, the Prototype Library implements this function already.
- Using ! is slightly faster and more concise than === 0 though not as readable.
- And here is endsWith if we need that too:
- We can use string.match() and a regular expression :
string.match() will return an array of matching substrings if found, otherwise null.
- A little more reusable function:
First, lets extend the string object, we think using the variable ‘string’ is works better than ‘needle’ in the context of making it more readable.
- Then we use it like this: