• support@answerspoint.com

How to check if a string “StartsWith” another string?

1946

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.

1Answer


0

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:

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

    Facebook Share        
       
  • asked 9 years ago
  • viewed 1946 times
  • active 9 years ago

Best Rated Questions