JavaScript – check if string starts with

Here is a simple method to check is a string is starting with a prefix.

String.prototype.beginWith = function string$beginWith(prefix, caseSensitive) {
	var _caseSensitive = (typeof(caseSensitive) !== 'boolean') ? false : caseSensitive;
	if(_caseSensitive === true) {
		return (this.substr(0, prefix.length) === prefix);
	else {
		return (this.substr(0, prefix.length).toLowerCase() === prefix.toLowerCase());

Function is accepting two parameters. First one is the prefix we want to check if is placed on the beginning of the string and the second one is a Boolean parameter to specify if comparison is case sensitive or not. If is not specify or is not a Boolean value, it is considered to be false. Usage is simple and can be used anywhere in the code where a variable is a string type.

var mystring  = 'mytext123456789text';
mystring.beginWith('mytext') // returns true;
mystring.beginWith('Mytext', true) // returns false;

5 thoughts on “JavaScript – check if string starts with

  1. thiskman

    Hi Andrei,

    I would simplify your method and use String.indexOf(). So

    String.prototype.beginWith = function(prefix) {
    return this.indexOf(prefix) === 0;


    1. This might work, but comparison is always case sensitive.

      var str = "MyText";
      alert(str.indexOf("My")); // alert 0
      alert(str.indexOf("my")); // alert -1

      For cases when I want to check if a string is starting with a prefix no matter of case sensitivity, I would prefer first method.

  2. Pingback: JavaScript – check if string ends with … | Popescu Andrei Vlad

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s