Built-in classes like Array, Map and others are extendable also. Please note a very interesting thing. Built-in methods like filter , map and others – return new objects of exactly the inherited type PowerArray .
JavaScript also has four built-in objects: Array, Date, Math, and String. Each object has special-purpose properties and methods associated with it. JavaScript also has constructors for Boolean and Number types.
Learning JavaScript The built-in objects are Date, Math, String, Array, and Object. Each is used in a unique and not-quite-consistent way. Furthermore, newer versions of JavaScript (as found in Netscape "Atlas," currently in beta) implement several of these objects in a different manner than in Netscape 2.0.
String Replace All :
String.prototype.replaceAll = function(search, replace)
{
//if replace is not sent, return original string otherwise it will
//replace search string with 'undefined'.
if (replace === undefined) {
return this.toString();
}
return this.replace(new RegExp('[' + search + ']', 'g'), replace);
};
var str = 'ABCADRAE';
alert(str.replaceAll('A','X')); // output : XBCXDRXE
Here's another implementation of String.replaceAll()
method
String.prototype.replaceAll = function(search, replace) {
if (replace === undefined) {
return this.toString();
}
return this.split(search).join(replace);
}
The difference between this one and solution posted here is that this implementation handles correctly regexp special characters in strings as well as allows for word matching
Array.prototype.indexOf = Array.prototype.indexOf || function (item) {
for (var i=0; i < this.length; i++) {
if(this[i] === item) return i;
}
return -1;
};
Usage:
var list = ["my", "array", "contents"];
alert(list.indexOf("contents")); // outputs 2
There are a ton of String.prototype functions from James Padolsey
https://github.com/padolsey/string.prototype
These include:
String.prototype.format = function (values) {
var regex = /\{([\w-]+)(?:\:([\w\.]*)(?:\((.*?)?\))?)?\}/g;
var getValue = function (key) {
if (values == null || typeof values === 'undefined') return null;
var value = values[key];
var type = typeof value;
return type === 'string' || type === 'number' ? value : null;
};
return this.replace(regex, function (match) {
//match will look like {sample-match}
//key will be 'sample-match';
var key = match.substr(1, match.length - 2);
var value = getValue(key);
return value != null ? value : match;
});
};
Usage:
alert('Program: {key1} {key2}'.format({ 'key1' : 'Hello', 'key2' : 'World' })); //alerts Program: hello world
// left trim
String.prototype.ltrim = function () {
return this.replace(/^\s+/, '');
}
// right trim
String.prototype.rtrim = function () {
return this.replace(/\s+$/, '');
}
// left and right trim
String.prototype.trim = function () {
return this.ltrim().rtrim();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With