by Njål

String replaceAll in Javascript

imageIn Javascript the string.replace(“target”, ”replacement”) function only replaces the first occurrence of the target…

Here’s how you can add a replaceAll() metod to all Strings (similar to Extension Methods in C#).

String.prototype.replaceAll = function (orig, replacement) {
    return this.split(orig).join(replacement);
}

 

You can then write (anywhere in your code):

"a a b c".replaceAll("a","X"); //==> "X X b c"
by Njål

console.log and Internet Explorer

imageWhen coding/debugging JS I usually work with Chrome and console.log works like a charm. But when you test the same page in Internet Explorer you’ll get a javascript error.

If you then open Developer Tools in IE and hit refresh – the page will work 100% – since IE now has a console object (the developer tools window) it can log to.

The solution is to either remove all console.log statements – or add this at the top of your js file:

 

if console === undefined {
    console = { log : function(){}};
}