JavaScript常用脚本集锦9

异步加载CSS

function loadCSS( href, before, media ){
    "use strict";

    var ss = window.document.createElement( "link" );
    var ref = before || window.document.getElementsByTagName( "script" )[ 0 ];
    var sheets = window.document.styleSheets;
    ss.rel = "stylesheet";
    ss.href = href;

    ss.media = "only x";

    ref.parentNode.insertBefore( ss, ref );

    function toggleMedia(){
        var defined;
        for( var i = 0; i < sheets.length; i++ ){
            if( sheets[ i ].href && sheets[ i ].href.indexOf( href ) > -1 ){
                defined = true;
            }
        }
        if( defined ){
            ss.media = media || "all";
        }
        else {
            setTimeout( toggleMedia );
        }
    }
    toggleMedia();
    return ss;
}

代码来源:https://github.com/filamentgroup/loadCSS/blob/master/loadCSS.js

异步加载JavaScript

function loadJS( src, cb ){
    "use strict";
    var ref = window.document.getElementsByTagName( "script" )[ 0 ];
    var script = window.document.createElement( "script" );
    script.src = src;
    script.async = true;
    ref.parentNode.insertBefore( script, ref );
    if (cb && typeof(cb) === "function") {
        script.onload = cb;
    }
    return script;
}

代码来源:https://github.com/filamentgroup/loadJS/blob/master/loadJS.js

简单的cookie操作

function cookie( name, value, days ){
    // if value is undefined, get the cookie value
    if( value === undefined ){
        var cookiestring = "; " + window.document.cookie;
        var cookies = cookiestring.split( "; " + name + "=" );
        if ( cookies.length === 2 ){
            return cookies.pop().split( ";" ).shift();
        }
        return null;
    }
    else {
        // if value is a false boolean, we'll treat that as a delete
        if( value === false ){
            days = -1;
        }
        var expires;
        if ( days ) {
            var date = new Date();
            date.setTime( date.getTime() + ( days * 24 * 60 * 60 * 1000 ) );
            expires = "; expires="+date.toGMTString();
        }
        else {
            expires = "";
        }
        window.document.cookie = name + "=" + value + expires + "; path=/";
    }
}

代码连接:https://github.com/filamentgroup/cookie/blob/master/cookie.js

数组原型拓展方法

/*
 * Array prototype extensions. Doesn't depend on any
 * other code. Doens't overwrite existing methods.
 *
 * Adds forEach, every, some, map, filter, indexOf and unique.
 *
 * Copyright (c) 2006 J?rn Zaefferer
 *
 * Dual licensed under the MIT and GPL licenses:
 *   http://www.opensource.org/licenses/mit-license.php
 *   http://www.gnu.org/licenses/gpl.html
 *
 */

(function() {

    /**
     * Adds a given method under the given name 
     * to the Array prototype if it doesn't
     * currently exist.
     *
     * @private
     */
    function add(name, method) {
        if( !Array.prototype[name] ) {
            Array.prototype[name] = method;
        }
    };

    /**
     * Executes a provided function once per array element.
     *
     * @example var stuff = "";
     * ["foo", "bar"].forEach(function(element, index, array) {
     *   stuff += element;
     * });
     * @result "foobar";
     *
     * @param Function handler Function to execute for each element.
     * @param Object scope (optional) Object to use as 'this' when executing handler.
     * @name forEach
     * @type undefined
     * @cat Plugins/Methods/Array
     */
    add("forEach", function(handler, scope) {
        scope = scope || window;
        for( var i = 0; i < this.length; i++)
            handler.call(scope, this[i], i, this);
    });

    /**
     * Tests whether all elements in the array pass the test
     * implemented by the provided function.
     *
     * @example [12, 54, 18, 130, 44].every(function(element, index, array) {
     *   return element >= 10;
     * });
     * @result true;
     *
     * @example [12, 5, 8, 130, 44].every(function(element, index, array) {
     *   return element >= 10;
     * });
     * @result false;
     *
     * @param Function handler Function to execute for each element.
     * @param Object scope (optional) Object to use as 'this' when executing handler.
     * @name every
     * @type Boolean
     * @cat Plugins/Methods/Array
     */
    add("every", function(handler, scope) {
        scope = scope || window;
        for( var i = 0; i < this.length; i++)
            if( !handler.call(scope, this[i], i, this) )
                return false;
        return true;
    });

    /**
     * Tests whether at least one element in the array passes the test
     * implemented by the provided function.
     *
     * @example [12, 5, 8, 1, 44].some(function(element, index, array) {
     *   return element >= 10;
     * });
     * @result true;
     *
     * @example [2, 5, 8, 1, 4].some(function(element, index, array) {
     *   return element >= 10;
     * });
     * @result false;
     *
     * @param Function handler Function to execute for each element.
     * @param Object scope (optional) Object to use as 'this' when executing handler.
     * @name some
     * @type Boolean
     * @cat Plugins/Methods/Array
     */
    add("some", function(handler, scope) {
        scope = scope || window;
        for( var i = 0; i < this.length; i++)
            if( handler.call(scope, this[i], i, this) )
                return true;
        return false;
    });

    /**
     * Creates a new array with the results of
     * calling a provided function on every element in this array.
     *
     * @example ["hello", "Array", "WORLD"].map(function(element, index, array) {
     *   return element.toUpperCase();
     * });
     * @result ["HELLO", "ARRAY", "WORLD"];
     *
     * @example [1, 4, 9].map(Math.sqrt);
     * @result [1, 2, 3];
     *
     * @param Function handler Function to execute for each element.
     * @param Object scope (optional) Object to use as 'this' when executing handler.
     * @name map
     * @type Array
     * @cat Plugins/Methods/Array
     */
    add("map", function(handler, scope) {
        scope = scope || window;
        var r = [];
        for( var i = 0; i < this.length; i++)
            r[r.length] = handler.call(scope, this[i], i, this);
        return r;
    });

    /**
     * Creates a new array with all elements that pass
     * the test implemented by the provided function.
     *
     * @example [12, 5, 8, 1, 44].filter(function(element, index, array) {
     *   return element >= 10;
     * });
     * @result [12, 44];
     *
     * @param Function handler Function to execute for each element.
     * @param Object scope (optional) Object to use as 'this' when executing handler.
     * @name filter
     * @type Array
     * @cat Plugins/Methods/Array
     */
    add("filter", function(handler, scope) {
        scope = scope || window;
        var r = [];
        for( var i = 0; i < this.length; i++)
            if( handler.call(scope, this[i], i, this) )
                r[r.length] = this[i];
        return r;
    });

    /**
     * Returns the first index at which a given element can
     * be found in the array, or -1 if it is not present.
     *
     * @example [12, 5, 8, 5, 44].indexOf(5);
     * @result 1;
     *
     * @example [12, 5, 8, 5, 44].indexOf(5, 2);
     * @result 3;
     *
     * @param Object subject Object to search for
     * @param Number offset (optional) Index at which to start searching
     * @name filter
     * @type Array
     * @cat Plugins/Methods/Array
     */
    add("indexOf", function(subject, offset) {
        for( var i = offset || 0; i < this.length; i++)
            if ( this[i] === subject )
                return i;
        return -1;
    });

    /**
     * Returns a new array that contains all unique elements
     * of this array.
     *
     * @example [1, 2, 1, 4, 5, 4].unique();
     * @result [1, 2, 4, 5]
     *
     * @name unique
     * @type Array
     * @cat Plugins/Methods/Array
     */
    add("unique", function() {
        return this.filter(function(element, index, array) {
            return array.indexOf(element) >= index;
        });
    });

})();   

链接地址:https://github.com/vitch/jquery-methods/edit/master/array.js

日期原型拓展方法

    /*
     * Date prototype extensions. Doesn't depend on any
     * other code. Doens't overwrite existing methods.
     *
     * Adds dayNames, abbrDayNames, monthNames and abbrMonthNames static properties and isLeapYear,
     * isWeekend, isWeekDay, getDaysInMonth, getDayName, getMonthName, getDayOfYear, getWeekOfYear,
     * setDayOfYear, addYears, addMonths, addDays, addHours, addMinutes, addSeconds methods
     *
     * Copyright (c) 2006 J?rn Zaefferer and Brandon Aaron (brandon.aaron@gmail.com || http://brandonaaron.net)
     *
     * Additional methods and properties added by Kelvin Luck: firstDayOfWeek, dateFormat, zeroTime, asString, fromString -
     * I've added my name to these methods so you know who to blame if they are broken!
     * 
     * Dual licensed under the MIT and GPL licenses:
     *   http://www.opensource.org/licenses/mit-license.php
     *   http://www.gnu.org/licenses/gpl.html
     *
     */

    /**
     * An Array of day names starting with Sunday.
     * 
     * @example dayNames[0]
     * @result 'Sunday'
     *
     * @name dayNames
     * @type Array
     * @cat Plugins/Methods/Date
     */
    Date.dayNames = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];

    /**
     * An Array of abbreviated day names starting with Sun.
     * 
     * @example abbrDayNames[0]
     * @result 'Sun'
     *
     * @name abbrDayNames
     * @type Array
     * @cat Plugins/Methods/Date
     */
    Date.abbrDayNames = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];

    /**
     * An Array of month names starting with Janurary.
     * 
     * @example monthNames[0]
     * @result 'January'
     *
     * @name monthNames
     * @type Array
     * @cat Plugins/Methods/Date
     */
    Date.monthNames = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];

    /**
     * An Array of abbreviated month names starting with Jan.
     * 
     * @example abbrMonthNames[0]
     * @result 'Jan'
     *
     * @name monthNames
     * @type Array
     * @cat Plugins/Methods/Date
     */
    Date.abbrMonthNames = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];

    /**
     * The first day of the week for this locale.
     *
     * @name firstDayOfWeek
     * @type Number
     * @cat Plugins/Methods/Date
     * @author Kelvin Luck
     */
    Date.firstDayOfWeek = 1;

    /**
     * The format that string dates should be represented as (e.g. 'dd/mm/yyyy' for UK, 'mm/dd/yyyy' for US, 'yyyy-mm-dd' for Unicode etc).
     *
     * @name format
     * @type String
     * @cat Plugins/Methods/Date
     * @author Kelvin Luck
     */
    Date.format = 'dd/mm/yyyy';
    //Date.format = 'mm/dd/yyyy';
    //Date.format = 'yyyy-mm-dd';
    //Date.format = 'dd mmm yy';

    /**
     * The first two numbers in the century to be used when decoding a two digit year. Since a two digit year is ambiguous (and date.setYear
     * only works with numbers < 99 and so doesn't allow you to set years after 2000) we need to use this to disambiguate the two digit year codes.
     *
     * @name format
     * @type String
     * @cat Plugins/Methods/Date
     * @author Kelvin Luck
     */
    Date.fullYearStart = '20';

    (function() {

        /**
         * Adds a given method under the given name 
         * to the Date prototype if it doesn't
         * currently exist.
         *
         * @private
         */
        function add(name, method) {
            if( !Date.prototype[name] ) {
                Date.prototype[name] = method;
            }
        };

        /**
         * Checks if the year is a leap year.
         *
         * @example var dtm = new Date("01/12/2008");
         * dtm.isLeapYear();
         * @result true
         *
         * @name isLeapYear
         * @type Boolean
         * @cat Plugins/Methods/Date
         */
        add("isLeapYear", function() {
            var y = this.getFullYear();
            return (y%4==0 && y%100!=0) || y%400==0;
        });

        /**
         * Checks if the day is a weekend day (Sat or Sun).
         *
         * @example var dtm = new Date("01/12/2008");
         * dtm.isWeekend();
         * @result false
         *
         * @name isWeekend
         * @type Boolean
         * @cat Plugins/Methods/Date
         */
        add("isWeekend", function() {
            return this.getDay()==0 || this.getDay()==6;
        });

        /**
         * Check if the day is a day of the week (Mon-Fri)
         * 
         * @example var dtm = new Date("01/12/2008");
         * dtm.isWeekDay();
         * @result false
         * 
         * @name isWeekDay
         * @type Boolean
         * @cat Plugins/Methods/Date
         */
        add("isWeekDay", function() {
            return !this.isWeekend();
        });

        /**
         * Gets the number of days in the month.
         * 
         * @example var dtm = new Date("01/12/2008");
         * dtm.getDaysInMonth();
         * @result 31
         * 
         * @name getDaysInMonth
         * @type Number
         * @cat Plugins/Methods/Date
         */
        add("getDaysInMonth", function() {
            return [31,(this.isLeapYear() ? 29:28),31,30,31,30,31,31,30,31,30,31][this.getMonth()];
        });

        /**
         * Gets the name of the day.
         * 
         * @example var dtm = new Date("01/12/2008");
         * dtm.getDayName();
         * @result 'Saturday'
         * 
         * @example var dtm = new Date("01/12/2008");
         * dtm.getDayName(true);
         * @result 'Sat'
         * 
         * @param abbreviated Boolean When set to true the name will be abbreviated.
         * @name getDayName
         * @type String
         * @cat Plugins/Methods/Date
         */
        add("getDayName", function(abbreviated) {
            return abbreviated ? Date.abbrDayNames[this.getDay()] : Date.dayNames[this.getDay()];
        });

        /**
         * Gets the name of the month.
         * 
         * @example var dtm = new Date("01/12/2008");
         * dtm.getMonthName();
         * @result 'Janurary'
         *
         * @example var dtm = new Date("01/12/2008");
         * dtm.getMonthName(true);
         * @result 'Jan'
         * 
         * @param abbreviated Boolean When set to true the name will be abbreviated.
         * @name getDayName
         * @type String
         * @cat Plugins/Methods/Date
         */
        add("getMonthName", function(abbreviated) {
            return abbreviated ? Date.abbrMonthNames[this.getMonth()] : Date.monthNames[this.getMonth()];
        });

        /**
         * Get the number of the day of the year.
         * 
         * @example var dtm = new Date("01/12/2008");
         * dtm.getDayOfYear();
         * @result 11
         * 
         * @name getDayOfYear
         * @type Number
         * @cat Plugins/Methods/Date
         */
        add("getDayOfYear", function() {
            var tmpdtm = new Date("1/1/" + this.getFullYear());
            return Math.floor((this.getTime() - tmpdtm.getTime()) / 86400000);
        });

        /**
         * Get the number of the week of the year.
         * 
         * @example var dtm = new Date("01/12/2008");
         * dtm.getWeekOfYear();
         * @result 2
         * 
         * @name getWeekOfYear
         * @type Number
         * @cat Plugins/Methods/Date
         */
        add("getWeekOfYear", function() {
            return Math.ceil(this.getDayOfYear() / 7);
        });

        /**
         * Set the day of the year.
         * 
         * @example var dtm = new Date("01/12/2008");
         * dtm.setDayOfYear(1);
         * dtm.toString();
         * @result 'Tue Jan 01 2008 00:00:00'
         * 
         * @name setDayOfYear
         * @type Date
         * @cat Plugins/Methods/Date
         */
        add("setDayOfYear", function(day) {
            this.setMonth(0);
            this.setDate(day);
            return this;
        });

        /**
         * Add a number of years to the date object.
         * 
         * @example var dtm = new Date("01/12/2008");
         * dtm.addYears(1);
         * dtm.toString();
         * @result 'Mon Jan 12 2009 00:00:00'
         * 
         * @name addYears
         * @type Date
         * @cat Plugins/Methods/Date
         */
        add("addYears", function(num) {
            this.setFullYear(this.getFullYear() + num);
            return this;
        });

        /**
         * Add a number of months to the date object.
         * 
         * @example var dtm = new Date("01/12/2008");
         * dtm.addMonths(1);
         * dtm.toString();
         * @result 'Tue Feb 12 2008 00:00:00'
         * 
         * @name addMonths
         * @type Date
         * @cat Plugins/Methods/Date
         */
        add("addMonths", function(num) {
            var tmpdtm = this.getDate();

            this.setMonth(this.getMonth() + num);

            if (tmpdtm > this.getDate())
                this.addDays(-this.getDate());

            return this;
        });

        /**
         * Add a number of days to the date object.
         * 
         * @example var dtm = new Date("01/12/2008");
         * dtm.addDays(1);
         * dtm.toString();
         * @result 'Sun Jan 13 2008 00:00:00'
         * 
         * @name addDays
         * @type Date
         * @cat Plugins/Methods/Date
         */
        add("addDays", function(num) {
            var timezoneOffsetBefore = this.getTimezoneOffset(),
                timezoneOffsetAfter;
            this.setTime(this.getTime() + (num*86400000) );
            timezoneOffsetAfter = this.getTimezoneOffset();

            // If the timezone has changed between days then adjust the time to reflect this
            if(timezoneOffsetAfter !== timezoneOffsetBefore){
                    this.setTime(this.getTime() + ((timezoneOffsetAfter-timezoneOffsetBefore) * 60 * 1000));
            }
            return this;
        });

        /**
         * Add a number of hours to the date object.
         * 
         * @example var dtm = new Date("01/12/2008");
         * dtm.addHours(24);
         * dtm.toString();
         * @result 'Sun Jan 13 2008 00:00:00'
         * 
         * @name addHours
         * @type Date
         * @cat Plugins/Methods/Date
         */
        add("addHours", function(num) {
            this.setHours(this.getHours() + num);
            return this;
        });

        /**
         * Add a number of minutes to the date object.
         * 
         * @example var dtm = new Date("01/12/2008");
         * dtm.addMinutes(60);
         * dtm.toString();
         * @result 'Sat Jan 12 2008 01:00:00'
         * 
         * @name addMinutes
         * @type Date
         * @cat Plugins/Methods/Date
         */
        add("addMinutes", function(num) {
            this.setMinutes(this.getMinutes() + num);
            return this;
        });

        /**
         * Add a number of seconds to the date object.
         * 
         * @example var dtm = new Date("01/12/2008");
         * dtm.addSeconds(60);
         * dtm.toString();
         * @result 'Sat Jan 12 2008 00:01:00'
         * 
         * @name addSeconds
         * @type Date
         * @cat Plugins/Methods/Date
         */
        add("addSeconds", function(num) {
            this.setSeconds(this.getSeconds() + num);
            return this;
        });

        /**
         * Sets the time component of this Date to zero for cleaner, easier comparison of dates where time is not relevant.
         * 
         * @example var dtm = new Date();
         * dtm.zeroTime();
         * dtm.toString();
         * @result 'Sat Jan 12 2008 00:01:00'
         * 
         * @name zeroTime
         * @type Date
         * @cat Plugins/Methods/Date
         * @author Kelvin Luck
         */
        add("zeroTime", function() {
            this.setMilliseconds(0);
            this.setSeconds(0);
            this.setMinutes(0);
            this.setHours(0);
            return this;
        });

        /**
         * Returns a string representation of the date object according to Date.format.
         * (Date.toString may be used in other places so I purposefully didn't overwrite it)
         * 
         * @example var dtm = new Date("01/12/2008");
         * dtm.asString();
         * @result '12/01/2008' // (where Date.format == 'dd/mm/yyyy'
         * 
         * @name asString
         * @type Date
         * @cat Plugins/Methods/Date
         * @author Kelvin Luck
         */
        add("asString", function(format) {
            var r = format || Date.format;
            return r
                .split('yyyy').join(this.getFullYear())
                .split('yy').join((this.getFullYear() + '').substring(2))
                .split('dd').join(_zeroPad(this.getDate()))
                .split('d').join(this.getDate())
                .split('DD').join(this.getDayName(false))
                .split('D').join(this.getDayName(true))
                .split('mmmm').join(this.getMonthName(false))
                .split('mmm').join(this.getMonthName(true))
                .split('mm').join(_zeroPad(this.getMonth()+1))
                .split('hh').join(_zeroPad(this.getHours()))
                .split('min').join(_zeroPad(this.getMinutes()))
                .split('ss').join(_zeroPad(this.getSeconds()));
        });

        /**
         * Returns a new date object created from the passed String according to Date.format or false if the attempt to do this results in an invalid date object
         * (We can't simple use Date.parse as it's not aware of locale and I chose not to overwrite it incase it's functionality is being relied on elsewhere)
         *
         * @example var dtm = Date.fromString("12/01/2008");
         * dtm.toString();
         * @result 'Sat Jan 12 2008 00:00:00' // (where Date.format == 'dd/mm/yyyy'
         * 
         * @name fromString
         * @type Date
         * @cat Plugins/Methods/Date
         * @author Kelvin Luck
         */
        Date.fromString = function(s, format)
        {
            var f = format || Date.format,
                d = new Date('01/01/1977'),
                mLength = 0,
                iM, iD, iY,
                i, mStr;

            iM = f.indexOf('mmmm');
            if (iM > -1) {
                for (i=0; i<Date.monthNames.length; i++) {
                    mStr = s.substr(iM, Date.monthNames[i].length);
                    if (Date.monthNames[i] == mStr) {
                        mLength = Date.monthNames[i].length - 4;
                        break;
                    }
                }
                d.setMonth(i);
            } else {
                iM = f.indexOf('mmm');
                if (iM > -1) {
                    mStr = s.substr(iM, 3);
                    for (i=0; i<Date.abbrMonthNames.length; i++) {
                        if (Date.abbrMonthNames[i] == mStr) break;
                    }
                    d.setMonth(i);
                } else {
                    d.setMonth(Number(s.substr(f.indexOf('mm'), 2)) - 1);
                }
            }

            iY = f.indexOf('yyyy');

            if (iY > -1) {
                if (iM < iY)
                {
                    iY += mLength;
                }
                d.setFullYear(Number(s.substr(iY, 4)));
            } else {
                if (iM < iY)
                {
                    iY += mLength;
                }
                // TODO - this doesn't work very well - are there any rules for what is meant by a two digit year?
                d.setFullYear(Number(Date.fullYearStart + s.substr(f.indexOf('yy'), 2)));
            }
            iD = f.indexOf('dd');
            if (iM < iD)
            {
                iD += mLength;
            }
            d.setDate(Number(s.substr(iD, 2)));
            if (isNaN(d.getTime())) {
                return false;
            }
            return d;
        };

        // utility method
        var _zeroPad = function(num) {
            var s = '0'+num;
            return s.substring(s.length-2)
            //return ('0'+num).substring(-2); // doesn't work on IE :(
        };

    })();

链接地址:https://github.com/vitch/jquery-methods/edit/master/date.js

字符串原型拓展方法

/*
 * String prototype extensions. Doesn't depend on any
 * other code. Doens't overwrite existing methods.
 *
 * Adds trim, camelize, startsWith, endsWith, truncate and stripTags.
 *
 * Copyright (c) 2006 J?rn Zaefferer
 *
 * Dual licensed under the MIT and GPL licenses:
 *   http://www.opensource.org/licenses/mit-license.php
 *   http://www.gnu.org/licenses/gpl.html
 *
 */

(function() {

    /**
     * Adds a given method under the given name 
     * to the String prototype if it doesn't
     * currently exist.
     *
     * @private
     */
    function add(name, method) {
        if( !String.prototype[name] ) {
            String.prototype[name] = method;
        }
    }

    /**
     * Returns a string with with leading and trailing whitespace removed.
     *
     * @example " Hello Boys and Girls!   ".trim()
     * @result "Hello Boys and Girls!"
     *
     * @name trim
     * @type String
     * @cat Plugins/Methods/String
     */
    add("trim", function(){ 
        return this.replace(/(^\s+|\s+$)/g, "");
    });

    /**
     * Return a camelized String, removing all underscores and dashes
     * and replacing the next character with it's uppercase representation.
     *
     * @example "font-weight".camelize()
     * @result "fontWeight"
     *
     * @example "border_width_bottom".camelize()
     * @result "borderWidthBottom"
     *
     * @example "border_width-bottom".camelize()
     * @result "borderWidthBottom"
     *
     * @name camelize
     * @type String
     * @cat Plugins/Methods/String
     */
    add("camelize", function() {
        return this.replace( /[-_]([a-z])/ig, function(z,b){ return b.toUpperCase();} );
    });

    /**
     * Tests if this string starts with a prefix.
     *
     * An optional offset specifies where to start searching,
     * default is 0 (start of the string).
     *
     * Returns false if the offset is negative or greater than the length
     * of this string.
     *
     * @example "goldvein".startsWith("go")
     * @result true
     * 
     * @example "goldvein".startsWith("god")
     * @result false
     *
     * @example "goldvein".startsWith("ld", 2)
     * @result true
     * 
     * @example "goldvein".startsWith("old", 2)
     * @result false
     *
     * @name startsWith
     * @type Boolean
     * @param prefix The prefix to test
     * @param offset (optional) From where to start testing
     * @cat Plugins/Methods/String
     */

    add("startsWith", function(prefix, offset) {
        var offset = offset || 0;
        if(offset < 0 || offset > this.length) return false;
        return this.substring(offset, offset + prefix.length) == prefix;
    });

    /**
     * Tests if this string ends with the specified suffix.
     *
     * @example "goldvein".endsWith("ein")
     * @result true
     *
     * @example "goldvein".endsWith("vei")
     * @result false
     *
     * @name endsWith
     * @type Boolean
     * @param suffix The suffix to test
     * @cat Plugins/Methods/String
     */
    add("endsWith", function(suffix) {
        return this.substring(this.length - suffix.length) == suffix;
    });

    /**
     * Returns a new String that is no longer than a certain length.
     *
     * @example "thisistenc ".truncate(5);
     * @result "th..."
     *
     * @example "thisistenc ".truncate(5, "x")
     * @result "thisx"
     *
     * @name truncate
     * @type String
     * @param Number length (optional) The maximum length of the returned string, default is 30
     * @param String suffix (optional) The suffix to append to the truncated string, default is "..."
     * @cat Plugins/Methods/String
     */
    add("truncate", function(length, suffix) {
        length = length || 30;
        suffix = suffix === undefined ? "..." : suffix;
        return this.length > length ? 
            this.slice(0, length - suffix.length) + suffix : this;
    });

    /**
     * Returns a new String with all tags stripped.
     *
     * @example "<div id='hi'>Bla</div>".stripTags()
     * @result "Bla"
     *
     * @name stripTags
     * @type String
     * @cat Plugins/Methods/String
     */
    add("stripTags", function() {
        return this.replace(/<\/?[^>]+>/gi, '');
    });

})();

https://github.com/vitch/jquery-methods/blob/master/string.js

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值