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;
Advertisements