How to check if a string "StartsWith" another string?
data.substring(0, input.length) === input
You can use ECMAScript 6's String.prototype.startsWith()
method. It's supported in all major browsers. However, if you want to use it in a browser that is unsupported you'll want to use a shim/polyfill to add it on those browsers. Creating an implementation that complies with all the details laid out in the spec is a little complicated. If you want a faithful shim, use either:
- Matthias Bynens's
String.prototype.startsWith
shim, or - The es6-shim, which shims as much of the ES6 spec as possible, including
String.prototype.startsWith
.
Once you've shimmed the method (or if you're only supporting browsers and JavaScript engines that already have it), you can use it like this:
console.log("Hello World!".startsWith("He")); // true
var haystack = "Hello world";
var prefix = 'orl';
console.log(haystack.startsWith(prefix)); // false
Another alternative with .lastIndexOf
:
haystack.lastIndexOf(needle) === 0
This looks backwards through haystack
for an occurrence of needle
starting from index string length of haystack
back to zero. In other words, it only checks if haystack
starts with needle
.
lastIndexOf
provides a second optional parameter 'fromIndex'. If given, the backwards search starts at this given index position and traverses back to index zero. But we must not specify any other fromIndex than the very last index, otherwise the search might overlook something.
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.