Usefull JavaScript’s & jQuery Code

#1 create a prototype function for e.g. a replaceAll function for strings:

String.prototype.replaceAll = function(search, replacement) {
     var target = this;
     return target.replace(new RegExp(search, 'g'), replacement);
};

Useage:

var test1, test2;

var str = “aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa”

test =  str .replaceAll("a", "c")
"cccccccccccccccccccccccccccccc"

//combineable
test2 =  str.replace("a", "b") .replaceAll("a", "c") 
"bccccccccccccccccccccccccccccc"

jQuery

Example:

$("body").find("div").each(function() {
    $(this).setRandomColor();
});

Add a Function to jQuery

$.fn.setRandomColor = function() {
    function getRandomColor() {
        var letters = '0123456789ABCDEF';
        var color = '#';
        for (var i = 0; i < 6; i++) {
            color += letters[Math.floor(Math.random() * 16)];
        }
        return color;
    };

    this.css("color", getRandomColor());
};

1 thought on “Usefull JavaScript’s & jQuery Code”

  1. function escapeHtml(unsafe) {
    return unsafe
    .replace(/&/g, "&amp;")
    .replace(/</g, "&lt;")
    .replace(/>/g, "&gt;")
    .replace(/"/g, "&quot;")
    .replace(/'/g, "&#039;");
    }

Leave a Reply to Peter Kilian Cancel reply

Your email address will not be published.