Thursday 12 September 2013

Create a endsWith Function in JavaScript.

Javascript does not have a endsWith function so we have to create it manually we use String prototype for create endsWith function.
if (typeof String.prototype.endsWith !== 'function') {
    String.prototype.endsWith = function(suffix) {
        return this.indexOf(suffix, this.length - suffix.length) !== -1;
    };
}
Then you can use it directly on string values.
var data = "Lorem ipsum dolor sit amet";
data.endsWith('amet'); //true



Create a Startwith Function in JavaScript.

Javascript does not have a StartsWith function so we have to create it manually we use String prototype for create StartsWith function.
if (typeof String.prototype.startsWith != 'function') {
  // see below for better implementation!
  String.prototype.startsWith = function (str){
    return this.indexOf(str) == 0;
  };
}
Then you can use it directly on string values.
"Hello World!".startsWith("He"); // true

var data = "Hello world";
var input = 'He';
data.startsWith(input); // true