PROWAREtech

articles » current » javascript » ie11 » ie11-prototype-string-padstart

JavaScript: IE11 String.padStart() Prototype/Function

Create the String.padStart() prototype for Internet Explorer 11.

Still developing for IE11? Well, this prototype is used to pad the start of strings on IE11.

Note: this prototype requires the repeat prototype for IE11.


if (!String.prototype.padStart) {
	String.prototype.padStart = function (targetLength, padString) {
		targetLength = targetLength >> 0; //truncate if number or convert non-number to 0;
		padString = String((typeof padString !== 'undefined' ? padString : ' '));
		if (this.length > targetLength) {
			return String(this);
		}
		else {
			targetLength = targetLength - this.length;
			if (targetLength > padString.length) {
				padString += padString.repeat(targetLength / padString.length); //append to original to ensure we are longer than needed
			}
			return padString.slice(0, targetLength) + String(this);
		}
	};
}

Using the above code snippet:


if (!String.prototype.padStart) {
	String.prototype.padStart = function (targetLength, padString) {
		targetLength = targetLength >> 0; //truncate if number or convert non-number to 0;
		padString = String((typeof padString !== 'undefined' ? padString : ' '));
		if (this.length > targetLength) {
			return String(this);
		}
		else {
			targetLength = targetLength - this.length;
			if (targetLength > padString.length) {
				padString += padString.repeat(targetLength / padString.length); //append to original to ensure we are longer than needed
			}
			return padString.slice(0, targetLength) + String(this);
		}
	};
}
alert("123".padStart(10, "#"));

This site uses cookies. Cookies are simple text files stored on the user's computer. They are used for adding features and security to this site. Read the privacy policy.
CLOSE