DCSIMG
אוסף סקריפטים לחיים קלים - Don't Worry, Be Happy - Development is FUN

אוסף סקריפטים לחיים קלים

פורסם בתאריך Feb 24 2011, 07:29 PM על ידי Arnold | ישנם תגובות

javascript היא שפה מגניבה, אך די מוגבלת.
אני מחכה בקוצר רוח לגרסה חדשה, אך בינתיים אספתי וכתבתי כמה פונקציות אשר יקלו על החיים שלכם

אוסף סקריפטים לחיים קלים
Format

ב net. אנחנו מכירים את ה String.Format, מתודה מדהימה לסידור נוח של טקסט.
כפי שידוע לכם (או לא ידוע) ב javascript אין לנו דבר זה, לכן הכנתי prototype לזה:

String.prototype.format = function() {
    var str = this,
        i = arguments.length;
      
    while (i--) {
        str = str.replace(new RegExp('\\{' + i + '\\}', 'gm'), arguments[i]);
    }
    return str;
};

אופן השימוש:

"My Name is {0}, my Phone is {1}".format(
    Arnold,
    050
);
Trim
String.prototype.trim = function () {
    return this.replace(new RegExp(/^\s+|\s+$/g), "");
};
String.prototype.ltrim = function () {
    return this.replace(/^\s+/, "");
};
String.prototype.rtrim = function () {
    return this.replace(/\s+$/, "");
};

אופן השימוש:

" space before, space after ".trim()
Multy Replace:

prototype ממש מגניב שמאפשר לעשות החלפה של פריטים מרובים.

במקום לרשום:

"this is string".replace("is", "a").replace("this", "This")

ניתן להשתמש ב prototype הבא:

String.prototype.multiReplace = function (hash) {
    var str = this, key;

    for (key in hash) {
        if (Object.prototype.hasOwnProperty.call(hash, key)) {
            str = str.replace(key, hash[key]);
        }
    }
    return str;
};
באופן הבא:
"this is string".multiReplace({"is":"a", "this":"This"})
Exists

לעתים אנחנו רוצים לבדוק אם האלמנט קיים בעמוד.
בעזרת jQuery ניתן לעשות את זה בצורה פשוטה:

jQuery.fn.Exists = function () {
    return ($(this).length > 0)
}

אופן השימוש:

if($("element").Exists()){
    alert("element Exists");
}
אני מקווה שהסקריפטים הללו יעזרו לכם לפתח אפליקציות מדהימות
סוף!