Tuesday, February 28, 2012

A JavaScript endsWith function

The following JavaScript function checks whether a string ends with a specified string.
function endsWith(str, s){
 var reg = new RegExp (s + "$");
 return reg.test(str);
}
The first argument is a string to be checked, the second one is a suffix to find. It returns true if the string ends with a specified string, and returns false if it does not. We use a "$" anchor to match the end of the string. The function is case-sensitive. Example:
var str="teens";
alert(endsWith(str, "ns"));
If you want to make the function into a method that could be used by all variables of a string type, you could use an object's prototype property:
String.prototype.endsWith = function(s){
 var reg = new RegExp(s + "$");
 return reg.test(this);
}
Then, you would use the function as follows:
alert(str.endsWith("ns"));

A JavaScript startsWith function

The previous function used the "$" anchor to match the end of a string. To match the start of a string, JavaScript regular expressions use a "^" (caret) anchor. This information allows us to write a function that would match the beginning of a string:
function startsWith(str, s){
 var reg = new RegExp("^" + s);
 return reg.test(str);
}

No comments:

Post a Comment