FANDOM


This pair of functions provide a quick way of testing whether one string starts or ends with another string.

Usage:

endsWith('Garden', 'en', true) // Returns true
startsWith('Garden', 'gard', false) // Returns false

function startsWith(str1, str2, matchCase) {
	if (str1.length < str2.length) return false;
	if (matchCase) {
		return (str1.substr(0, str2.length) == str2);
	} else {
		return (str1.toLowerCase().substr(0, str2.length)
		== str2.toLowerCase());
	}
}

function endsWith(str1, str2, matchCase) {
	if (str1.length < str2.length) return false;
	if (matchCase) {
		return (str1.substr(str2.length) == str2);
	} else {
		return (str1.toLowerCase().substr(str2.length)
	 	== str2.toLowerCase());
	}
}

Alternative Using Regular Expressions (untested)Edit

// lookInThisString is a string
// forThisString is a string parameter
// matchCase is an optional boolean parameter, defaults to false
//
function startsWith(lookInThisString, forThisString, matchCase) {
  var mookie = new RegExp("^" + forThisString,(matchCase)?"":"i");
  return mookie.test(lookInThisString);
}

function endsWith(lookInThisString, forThisString, matchCase) {
  var mookie = new RegExp(forThisString + "$",(matchCase)?"":"i");
  return mookie.test(lookInThisString);
}

Ad blocker interference detected!


Wikia is a free-to-use site that makes money from advertising. We have a modified experience for viewers using ad blockers

Wikia is not accessible if you’ve made further modifications. Remove the custom ad blocker rule(s) and the page will load as expected.