Javascript .replace Alternative
I am coding a template for eBay. However, eBay does not allow .replace. The code below is for a rollover tab section.When the user hovers over tab(a), the correspodning div div(a)
Solution 1:
You may try this as an alternative of replace
function
String.prototype.fakeReplace = function(str, newstr) {
returnthis.split(str).join(newstr);
};
var str = "Welcome javascript";
str = str.fakeReplace('javascript', '');
alert(str); // Welcome
DEMO.
Solution 2:
For a more efficient, but slightly longer method, use this:
String.prototype.myReplace = function(pattern, nw) {
var curidx = 0, len = this.length, patlen = pattern.length, res = "";
while(curidx < len) {
var nwidx = this.indexOf(pattern, curidx);
console.log(nwidx);
if(nwidx == -1) {
break;
}
res = res + this.substr(curidx, nwidx - curidx);
res = res + nw;
curidx = nwidx + patlen;
}
return res;
};
alert("Glee is awesome".myReplace("awesome", "very very very awesome"));
See it in action: little link.
Hope that helped!
Post a Comment for "Javascript .replace Alternative"