snippetjavascriptCritical
How to check if a string "StartsWith" another string?
Viewed 0 times
howcheckstartswithstringanother
Problem
How would I write the equivalent of C#'s
Note: This is an old question, and as pointed out in the comments ECMAScript 2015 (ES6) introduced the
String.StartsWith in JavaScript?var haystack = 'hello world';
var needle = 'he';
haystack.startsWith(needle) == trueNote: This is an old question, and as pointed out in the comments ECMAScript 2015 (ES6) introduced the
.startsWith method. However, at the time of writing this update (2015) browser support is far from complete.Solution
You can use ECMAScript 6's
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:
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.startsWithshim, 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)); // falseContext
Stack Overflow Q#646628, score: 1868
Revisions (0)
No revisions yet.