How to check if a string “StartsWith” another string?
How would I write the equivalent of C#'s String.StartsWith
in Javascript?
var data = 'hello world';
var input = 'he';
//data.startsWith(input) == true
Note: This is an older question, as pointed out in the comments ECMAScript 2015 (ES6) introduces startsWith, however, at the time of writing this update (2015) browser-support is far from complete.
Javascript
- asked 9 years ago
- B Butts
1Answer
You can implement this using String.prototype.substring
or String.prototype.slice
:
function stringStartsWith (string, prefix) {
return string.slice(0, prefix.length) == prefix;
}
Then you can use it like this:
stringStartsWith("Hello, World!", "He"); // true
stringStartsWith("Hello, World!", "orl"); // false
The difference between substring
and slice
is basically that slice
can take negative indexes, to manipulate characters from the end of the string. For example you could write the counterpart stringEndsWith
function by:
function stringEndsWith (string, suffix) {
return suffix == '' || string.slice(-suffix.length) == suffix;
}
Alternatively, you could use ECMAScript 6's String.prototype.startsWith()
method, but it's not yet supported in all browsers. You'll want to use a shim/polyfill to add it on browsers that don't support it. Creating an implementation that complies with all the details laid out in the spec is a little complicated, and the version defined in this answer won't do; 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:
"Hello World!".startsWith("He"); // true
var haystack = "Hello world";
var prefix = 'orl';
haystack.startsWith(prefix); // false
- answered 8 years ago
- Sunny Solu
Your Answer