Для получения полного доступа
зарегистрируйтесь.

Section:
Sub-section::
Languages:


Kosuha606  В основном веб языки, а вообще полиглот!
  • Reputation: 12
  • Snippets: 9
  • Revisions: 0

Впринципе ничего особенного, просто сетка на 12 колонок, привязанная к data параметрам

[data-rbk-container] { width: 1170px; margin: 0 auto; }
[data-rbk-row] { display: block; }
[data-rbk-row]:after, [data-rbk-row]:before { content: ' '; display: block; clear: both; height: 0; }
[data-rbk-col] { display: block; box-sizing: border-box; width: 50%; padding: 15px; float: left; }
[data-rbk-col="1"] { width: 8.333%; }
[data-rbk-col="2"] { width: 16.666%;}
[data-rbk-col="10"] { width: 83.333%;}
[data-rbk-col="3"] { width: 25%; }
[data-rbk-col="2.5"] { width: 20%; } /* for 5th colons */
[data-rbk-col="9"] { width: 75%; }
[data-rbk-col="4"] { width: 33.333%; }
[data-rbk-col="8"] { width: 66.666%; }
[data-rbk-col="5"] { width: 41.666%; }
[data-rbk-col="7"] { width: 58.333%; }
[data-rbk-col="11"] { width: 91.666%; }
[data-rbk-col="12"] { width: 100%; }

View Demo

Gravatar image
blacksmoke26  yii2, javascript, php, mysql, css, sass, html, sql
  • Reputation: 14
  • Snippets: 11
  • Revisions: 0
/**
 * Get timezones list
 * @return array
 */
function getTimeZones () {
	return [
		'Africa' => [
			'Africa/Algiers' => 'Algeria (+01:00)',
			'Africa/Gaborone' => 'Botswana (+02:00)',
			'Africa/Douala' => 'Cameroon (+01:00)',
			'Africa/Bangui' => 'Central African Republic (+01:00)',
			'Africa/Ndjamena' => 'Chad (+01:00)',
			'Africa/Kinshasa' => 'Democratic Republic of the Congo (+01:00)',
			'Africa/Djibouti' => 'Djibouti (+03:00)',
			'Africa/Cairo' => 'Egypt (+02:00)',
			'Africa/Malabo' => 'Equatorial Guinea (+01:00)',
			'Africa/Asmara' => 'Eritrea (+03:00)',
			'Africa/Addis_Ababa' => 'Ethiopia (+03:00)',
			'Africa/Libreville' => 'Gabon (+01:00)',
			'Africa/Banjul' => 'Gambia (+00:00)',
			'Africa/Accra' => 'Ghana (+00:00)',
			'Africa/Conakry' => 'Guinea (+00:00)',
			'Africa/Bissau' => 'Guinea-Bissau (+00:00)',
			'Africa/Abidjan' => 'Ivory Coast (+00:00)',
			'Africa/Nairobi' => 'Kenya (+03:00)',
			'Africa/Maseru' => 'Lesotho (+02:00)',
			'Africa/Monrovia' => 'Liberia (+00:00)',
			'Africa/Tripoli' => 'Libya (+02:00)',
			'Africa/Blantyre' => 'Malawi (+02:00)',
			'Africa/Bamako' => 'Mali (+00:00)',
			'Africa/Nouakchott' => 'Mauritania (+00:00)',
			'Africa/Casablanca' => 'Morocco (+01:00)',
			'Africa/Maputo' => 'Mozambique (+02:00)',
			'Africa/Windhoek' => 'Namibia (+01:00)',
			'Africa/Niamey' => 'Niger (+01:00)',
			'Africa/Lagos' => 'Nigeria (+01:00)',
			'Africa/Brazzaville' => 'Republic of the Congo (+01:00)',
			'Africa/Kigali' => 'Rwanda (+02:00)',
			'Africa/Sao_Tome' => 'Sao Tome and Principe (+00:00)',
			'Africa/Dakar' => 'Senegal (+00:00)',
			'Africa/Freetown' => 'Sierra Leone (+00:00)',
			'Africa/Mogadishu' => 'Somalia (+03:00)',
			'Africa/Johannesburg' => 'South Africa (+02:00)',
			'Africa/Juba' => 'South Sudan (+03:00)',
			'Africa/Khartoum' => 'Sudan (+03:00)',
			'Africa/Mbabane' => 'Swaziland (+02:00)',
			'Africa/Dar_es_Salaam' => 'Tanzania (+03:00)',
			'Africa/Lome' => 'Togo (+00:00)',
			'Africa/Tunis' => 'Tunisia (+01:00)',
			'Africa/Kampala' => 'Uganda (+03:00)',
			'Africa/El_Aaiun' => 'Western Sahara (+00:00)',
			'Africa/Lusaka' => 'Zambia (+02:00)',
			'Africa/Harare' => 'Zimbabwe (+02:00)',
		],

		'America' => [
			'America/Nassau' => 'Bahamas (-04:00)',
			'America/Belize' => 'Belize (-06:00)',
			'America/Noronha' => 'Brazil (-02:00)',
			'America/Tortola' => 'British Virgin Islands (-04:00)',
			'America/St_Johns' => 'Canada (-02:30)',
			'America/Cayman' => 'Cayman Islands (-05:00)',
			'America/Santiago' => 'Chile (-04:00)',
			'America/Bogota' => 'Colombia (-05:00)',
			'America/Costa_Rica' => 'Costa Rica (-06:00)',
			'America/Havana' => 'Cuba (-04:00)',
			'America/Curacao' => 'Curaçao (-04:00)',
			'America/Dominica' => 'Dominica (-04:00)',
			'America/Santo_Domingo' => 'Dominican Republic (-04:00)',
			'America/Guayaquil' => 'Ecuador (-05:00)',
			'America/El_Salvador' => 'El Salvador (-06:00)',
			'America/Cayenne' => 'French Guiana (-03:00)',
			'America/Godthab' => 'Greenland (-02:00)',
			'America/Grenada' => 'Grenada (-04:00)',
			'America/Guadeloupe' => 'Guadeloupe (-04:00)',
			'America/Guatemala' => 'Guatemala (-06:00)',
			'America/Guyana' => 'Guyana (-04:00)',
			'America/Port-au-Prince' => 'Haiti (-05:00)',
			'America/Tegucigalpa' => 'Honduras (-06:00)',
			'America/Jamaica' => 'Jamaica (-05:00)',
			'America/Martinique' => 'Martinique (-04:00)',
			'America/Mexico_City' => 'Mexico (-05:00)',
			'America/Montserrat' => 'Montserrat (-04:00)',
			'America/Managua' => 'Nicaragua (-06:00)',
			'America/Panama' => 'Panama (-05:00)',
			'America/Asuncion' => 'Paraguay (-04:00)',
			'America/Lima' => 'Peru (-05:00)',
			'America/Puerto_Rico' => 'Puerto Rico (-04:00)',
			'America/St_Kitts' => 'Saint Kitts and Nevis (-04:00)',
			'America/St_Lucia' => 'Saint Lucia (-04:00)',
			'America/Marigot' => 'Saint Martin (-04:00)',
			'America/Miquelon' => 'Saint Pierre and Miquelon (-02:00)',
			'America/St_Vincent' => 'Saint Vincent and the Grenadines (-04:00)',
			'America/Lower_Princes' => 'Sint Maarten (-04:00)',
			'America/Paramaribo' => 'Suriname (-03:00)',
			'America/Port_of_Spain' => 'Trinidad and Tobago (-04:00)',
			'America/Grand_Turk' => 'Turks and Caicos Islands (-04:00)',
			'America/St_Thomas' => 'U.S. Virgin Islands (-04:00)',
			'America/New_York' => 'United States (-04:00)',
			'America/Montevideo' => 'Uruguay (-03:00)',
			'Europe/Vatican' => 'Vatican (+02:00)',
			'America/Caracas' => 'Venezuela (-04:30)',
		],

		'Arctic' => [
			'Arctic/Longyearbyen' => 'Svalbard and Jan Mayen (+02:00)',
		],

		'Asia' => [
			'Asia/Thimphu' => 'Bhutan (+06:00)',
			'Asia/Phnom_Penh' => 'Cambodia (+07:00)',
			'Asia/Shanghai' => 'China (+08:00)',
			'Asia/Nicosia' => 'Cyprus (+03:00)',
			'Asia/Dili' => 'East Timor (+09:00)',
			'Asia/Tbilisi' => 'Georgia (+04:00)',
			'Asia/Hong_Kong' => 'Hong Kong (+08:00)',
			'Asia/Kolkata' => 'India (+05:30)',
			'Asia/Jakarta' => 'Indonesia (+07:00)',
			'Asia/Tehran' => 'Iran (+04:30)',
			'Asia/Baghdad' => 'Iraq (+03:00)',
			'Asia/Jerusalem' => 'Israel (+03:00)',
			'Asia/Tokyo' => 'Japan (+09:00)',
			'Asia/Amman' => 'Jordan (+03:00)',
			'Asia/Almaty' => 'Kazakhstan (+06:00)',
			'Asia/Kuwait' => 'Kuwait (+03:00)',
			'Asia/Bishkek' => 'Kyrgyzstan (+06:00)',
			'Asia/Vientiane' => 'Laos (+07:00)',
			'Asia/Beirut' => 'Lebanon (+03:00)',
			'Asia/Macau' => 'Macao (+08:00)',
			'Asia/Kuala_Lumpur' => 'Malaysia (+08:00)',
			'Asia/Ulaanbaatar' => 'Mongolia (+08:00)',
			'Asia/Rangoon' => 'Myanmar (+06:30)',
			'Asia/Kathmandu' => 'Nepal (+05:45)',
			'Asia/Pyongyang' => 'North Korea (+09:00)',
			'Asia/Muscat' => 'Oman (+04:00)',
			'Asia/Karachi' => 'Pakistan (+05:00)',
			'Asia/Gaza' => 'Palestinian Territory (+02:00)',
			'Asia/Manila' => 'Philippines (+08:00)',
			'Asia/Qatar' => 'Qatar (+03:00)',
			'Asia/Riyadh' => 'Saudi Arabia (+03:00)',
			'Asia/Singapore' => 'Singapore (+08:00)',
			'Asia/Seoul' => 'South Korea (+09:00)',
			'Asia/Colombo' => 'Sri Lanka (+05:30)',
			'Asia/Damascus' => 'Syria (+03:00)',
			'Asia/Taipei' => 'Taiwan (+08:00)',
			'Asia/Dushanbe' => 'Tajikistan (+05:00)',
			'Asia/Bangkok' => 'Thailand (+07:00)',
			'Asia/Ashgabat' => 'Turkmenistan (+05:00)',
			'Asia/Samarkand' => 'Uzbekistan (+05:00)',
			'Asia/Ho_Chi_Minh' => 'Vietnam (+07:00)',
			'Asia/Aden' => 'Yemen (+03:00)',
		],

		'Atlantic' => [
			'Atlantic/Cape_Verde' => 'Cape Verde (-01:00)',
			'Atlantic/Stanley' => 'Falkland Islands (-03:00)',
			'Atlantic/Faroe' => 'Faroe Islands (+01:00)',
			'Atlantic/Reykjavik' => 'Iceland (+00:00)',
			'Atlantic/St_Helena' => 'Saint Helena (+00:00)',
			'Atlantic/South_Georgia' => 'South Georgia and the South Sandwich Islands (-02:00)',
		],

		'Europe' => [
			'Europe/Minsk' => 'Belarus (+03:00)',
			'Europe/Zagreb' => 'Croatia (+02:00)',
			'Europe/Prague' => 'Czech Republic (+02:00)',
			'Europe/Copenhagen' => 'Denmark (+02:00)',
			'Europe/Tallinn' => 'Estonia (+03:00)',
			'Europe/Helsinki' => 'Finland (+03:00)',
			'Europe/Paris' => 'France (+02:00)',
			'Europe/Berlin' => 'Germany (+02:00)',
			'Europe/Gibraltar' => 'Gibraltar (+02:00)',
			'Europe/Athens' => 'Greece (+03:00)',
			'Europe/Guernsey' => 'Guernsey (+01:00)',
			'Europe/Budapest' => 'Hungary (+02:00)',
			'Europe/Dublin' => 'Ireland (+01:00)',
			'Europe/Isle_of_Man' => 'Isle of Man (+01:00)',
			'Europe/Rome' => 'Italy (+02:00)',
			'Europe/Jersey' => 'Jersey (+01:00)',
			'Europe/Riga' => 'Latvia (+03:00)',
			'Europe/Vaduz' => 'Liechtenstein (+02:00)',
			'Europe/Vilnius' => 'Lithuania (+03:00)',
			'Europe/Luxembourg' => 'Luxembourg (+02:00)',
			'Europe/Skopje' => 'Macedonia (+02:00)',
			'Europe/Malta' => 'Malta (+02:00)',
			'Europe/Chisinau' => 'Moldova (+03:00)',
			'Europe/Monaco' => 'Monaco (+02:00)',
			'Europe/Podgorica' => 'Montenegro (+02:00)',
			'Europe/Amsterdam' => 'Netherlands (+02:00)',
			'Europe/Oslo' => 'Norway (+02:00)',
			'Europe/Warsaw' => 'Poland (+02:00)',
			'Europe/Lisbon' => 'Portugal (+01:00)',
			'Europe/Bucharest' => 'Romania (+03:00)',
			'Europe/Kaliningrad' => 'Russia (+03:00)',
			'Europe/San_Marino' => 'San Marino (+02:00)',
			'Europe/Belgrade' => 'Serbia (+02:00)',
			'Europe/Bratislava' => 'Slovakia (+02:00)',
			'Europe/Ljubljana' => 'Slovenia (+02:00)',
			'Europe/Madrid' => 'Spain (+02:00)',
			'Europe/Stockholm' => 'Sweden (+02:00)',
			'Europe/Zurich' => 'Switzerland (+02:00)',
			'Europe/Istanbul' => 'Turkey (+03:00)',
			'Europe/Kiev' => 'Ukraine (+03:00)',
			'Europe/London' => 'United Kingdom (+01:00)',
		],

		'Indian' => [
			'Indian/Chagos' => 'British Indian Ocean Territory (+06:00)',
			'Indian/Christmas' => 'Christmas Island (+07:00)',
			'Indian/Cocos' => 'Cocos Islands (+06:30)',
			'Indian/Comoro' => 'Comoros (+03:00)',
			'Indian/Kerguelen' => 'French Southern Territories (+05:00)',
			'Indian/Antananarivo' => 'Madagascar (+03:00)',
			'Indian/Maldives' => 'Maldives (+05:00)',
			'Indian/Mauritius' => 'Mauritius (+04:00)',
			'Indian/Mayotte' => 'Mayotte (+03:00)',
			'Indian/Reunion' => 'Reunion (+04:00)',
			'Indian/Mahe' => 'Seychelles (+04:00)',
		],

		'Pacific' => [
			'Pacific/Rarotonga' => 'Cook Islands (-10:00)',
			'Pacific/Fiji' => 'Fiji (+12:00)',
			'Pacific/Tahiti' => 'French Polynesia (-10:00)',
			'Pacific/Guam' => 'Guam (+10:00)',
			'Pacific/Tarawa' => 'Kiribati (+12:00)',
			'Pacific/Majuro' => 'Marshall Islands (+12:00)',
			'Pacific/Chuuk' => 'Micronesia (+10:00)',
			'Pacific/Nauru' => 'Nauru (+12:00)',
			'Pacific/Noumea' => 'New Caledonia (+11:00)',
			'Pacific/Auckland' => 'New Zealand (+12:00)',
			'Pacific/Niue' => 'Niue (-11:00)',
			'Pacific/Norfolk' => 'Norfolk Island (+11:30)',
			'Pacific/Saipan' => 'Northern Mariana Islands (+10:00)',
			'Pacific/Palau' => 'Palau (+09:00)',
			'Pacific/Port_Moresby' => 'Papua New Guinea (+10:00)',
			'Pacific/Pitcairn' => 'Pitcairn (-08:00)',
			'Pacific/Apia' => 'Samoa (+13:00)',
			'Pacific/Guadalcanal' => 'Solomon Islands (+11:00)',
			'Pacific/Fakaofo' => 'Tokelau (+14:00)',
			'Pacific/Tongatapu' => 'Tonga (+13:00)',
			'Pacific/Funafuti' => 'Tuvalu (+12:00)',
			'Pacific/Johnston' => 'United States Minor Outlying Islands (-10:00)',
			'Pacific/Efate' => 'Vanuatu (+11:00)',
			'Pacific/Wallis' => 'Wallis and Futuna (+12:00)',
		],

		'Other' => [
			'UTC' => 'UTC',
		],
	];
}

/*******************
 * SIMPLE USAGE
 *******************/
print_r ( getTimeZones() );

Yii2 Example

\yii\helpers\Html::dropDownList('timezone', null, getTimeZones (), [
	'prompt' => '-- Choose --'
]);
Gravatar image
blacksmoke26  yii2, javascript, php, mysql, css, sass, html, sql
  • Reputation: 14
  • Snippets: 11
  • Revisions: 0
/**
 * Split the SQL dump code and return as queries array.
 * @param string $raw SQL code to parse
 * @return array List of queries
 */
function splitSqlText ( $raw ) {
	// the regex needs a trailing semicolon
	$raw = trim ( (string) $raw );

	if ( substr ( $raw, -1 ) !== ";") {
		$raw .= ";";
	}

	// i spent 3 days figuring out this line
	preg_match_all( "/(?>[^;']|(''|(?>'([^']|\\')*[^\\\]')".
		"))+;/ixU", $raw, $matches, PREG_SET_ORDER );

	$querySplit = [];

	foreach ( $matches as $match ) {
		// get rid of the trailing semicolon
		$querySplit[] = substr( $match[0], 0, -1 );
	}

	return $querySplit;
}
Gravatar image
blacksmoke26  yii2, javascript, php, mysql, css, sass, html, sql
  • Reputation: 14
  • Snippets: 11
  • Revisions: 0
/**
 * Validate MySQL Timestamp
 * @param string $value Value to check (Y-m-d h:i:s)
 * @return bool TRUE on valid | FALSE anyway
 */
function isTimestampValid ( $value ) {
	$date = array();
	if ( !preg_match ('/^(?<y>19\d\d|20\d\d)\-(?<m>0[1-9]|1[0-2])\-' .
		'(?<d>0\d|[1-2]\d|3[0-1]) (?<h>0\d|1\d|2[0-3]' .
		')\:(?<i>[0-5][0-9])\:(?<s>[0-5][0-9])$/', $value, $date) ) {
		return false;
	}

	return checkdate ( $date['m'], $date['d'], $date['y'] );
}

/************
 * EXAMPLE
 ***********/
var_dump ( isTimestampValid ('2016-09-10 23:21:09') );

/***********
 * OUTPUT
 **********/
# (bool) true
Gravatar image
blacksmoke26  yii2, javascript, php, mysql, css, sass, html, sql
  • Reputation: 14
  • Snippets: 11
  • Revisions: 0
/**
 * Generate mime types list using apache svn defination
 * @link http://php.net/manual/en/function.mime-content-type.php#107798
 * @return array [key=>value] pairs of mime types (extension=>mime_type)
 */
function generateMimeTypes () {
	$list = [];
	$url = 'http://svn.apache.org/repos/asf/httpd/httpd/trunk/docs/conf/mime.types';
    
	foreach ( @explode ( "\n", @file_get_contents ($url) ) as $x ) {
		if ( isset( $x[0] )
			&& $x[0] !== '#'
			&& preg_match_all ( '#([^\s]+)#', $x, $out )
			&& isset( $out[1] )
			&& ( $c = count ( $out[1] ) ) > 1 ) {
			for ( $i = 1; $i < $c; $i++ ) {
				$key = (string) $out[1][$i];
				$list[$key] = $out[1][0];
			}
		}
	}

	return @ksort($list, \SORT_STRING )
		? $list
		: [];
}

/************
 * EXAMPLE
 ***********/
print_r ( generateMimeTypes () );

/***********
 * OUTPUT
 **********/
 [
    '3dml' => 'text/vnd.in3d.3dml'
    '3ds' => 'image/x-3ds'
    '3g2' => 'video/3gpp2'
    '3gp' => 'video/3gpp'
    '7z' => 'application/x-7z-compressed'
    'aab' => 'application/x-authorware-bin'
    'aac' => 'audio/x-aac'
    'aam' => 'application/x-authorware-map'
    'aas' => 'application/x-authorware-seg'
    'abw' => 'application/x-abiword'
    'ac' => 'application/pkix-attr-cert'
    'acc' => 'application/vnd.americandynamics.acc'
    'ace' => 'application/x-ace-compressed'
    'acu' => 'application/vnd.acucobol'
    'acutc' => 'application/vnd.acucorp'
    'adp' => 'audio/adpcm'
    'aep' => 'application/vnd.audiograph'
    'afm' => 'application/x-font-type1'
    'afp' => 'application/vnd.ibm.modcap'
    'ahead' => 'application/vnd.ahead.space'
    'ai' => 'application/postscript'
    'aif' => 'audio/x-aiff',
    ...
]
Gravatar image
blacksmoke26  yii2, javascript, php, mysql, css, sass, html, sql
  • Reputation: 14
  • Snippets: 11
  • Revisions: 0
/**
 * Divide an array into a desired number of split lists
 * @link http://www.php.net/manual/en/function.array-chunk.php#75022
 * @param array $list The Array
 * @param int $size Partition Size
 * @return array The partitioned array
 */
function columnsPartition ( array $list, $size ) {
	$listLen = count ( $list );

	if ( !$listLen || $size < 1 ) {
		return [];
	}

	$partLen = floor ( $listLen / $size );
	$partRem = $listLen % $size;
	$partition = [];
	$mark = 0;

	for ( $px = 0; $px < $size; $px++ ) {
		$increment = ( $px < $partRem ) ? $partLen + 1 : $partLen;

		$partition[ $px ] = array_slice ( $list, $mark, $increment );
		$mark += $increment;
	}

	return $partition;
}

/************
 * EXAMPLE
 ***********/
var_dump ( columnsPartition(range('A','I'), 3) );

/***********
 * OUTPUT
 **********/
array (size=3)
  0 => 
    array (size=3)
      0 => string 'A' (length=1)
      1 => string 'B' (length=1)
      2 => string 'C' (length=1)
  1 => 
    array (size=3)
      0 => string 'D' (length=1)
      1 => string 'E' (length=1)
      2 => string 'F' (length=1)
  2 => 
    array (size=3)
      0 => string 'G' (length=1)
      1 => string 'H' (length=1)
      2 => string 'I' (length=1)
Gravatar image
blacksmoke26  yii2, javascript, php, mysql, css, sass, html, sql
  • Reputation: 14
  • Snippets: 11
  • Revisions: 0
/**
 * Strip text longer then given length
 * @param string $text Text to be stripped
 * @param int $length Length of chars to keep
 * @param string $glueChar (optional) Show when length exceeded
 * @return string|null Stripped text | Text was empty
 */
function getCharsByLength ( $text, $length, $glueChar = '...' ) {
	if ( !trim ($text ) ) {
		return null;
	}

	/** @var int $actualLength */
	$actualLength = function_exists('mb_strlen')
		? mb_strlen($text)
		: strlen($text);

	// desired length is same or less, return as it is
	if ( $actualLength <= $length ) {
		return $text;
	}

	return function_exists ( 'mb_substr' )
		? mb_substr ($text, 0, $length, 'utf8' ) . $glueChar
		: substr ($text, 0, $length ) . $glueChar;
}

/************
 * EXAMPLE
 ***********/
getCharsByLength ('Νο εαμ σθμμο vολθτπατ. Εα εστ ομνεσ ιμπερδιετ εφφιcιαντθρ', 10);

/***********
 * OUTPUT
 **********/
# Νο εαμ σθμ...
IStranger  PHP, SQL, JavaScript, Delphi. Yii
  • Reputation: 15
  • Snippets: 8
  • Revisions: 0

High-performance function checks whether specified array contains only integer values (or integer-numeric strings):


/**
 * Checks whether all elements of an array are integers (integer value or string with integer value).
 * Note: this is very efficient method can be used for array with 10000+ items.
 *
 * @param int[]|string[] $array One dimensional array to check
 *
 * @return bool
 */ 
function hasOnlyIntEntries(array $array)
{
    return ctype_digit(join('', $array));
}
IStranger  PHP, SQL, JavaScript, Delphi. Yii
  • Reputation: 15
  • Snippets: 8
  • Revisions: 0

Often we need remove CSS classes that begin with certain string. For example: has-state-active, has-state-pending, has-state-disabled. Easiest way is to use wildcards: has-state-*.

Following function supports them (requires jQuery):

/**
 * Removes CSS classes of element using wildcards:
 *
 * @example
 * <code><pre>
 *
 *          // create some element
 *      var $element = $('<div id="#some-element"/>')
 *                          .addClass('base-class has-state-active item item-75')
 *                          .appendTo('body');
 *
 *          // remove classes with few prefixes
 *      removeClassWildcard( $element, 'has-state-* item-*');
 *
 *          // display element classes
 *      console.log($element.attr('class'));    // >> "base-class item"
 *
 * </pre></code>
 *
 * @param {jQuery|*}    $element
 * @param {String}      removals        Classes to delete, for example: 'foo-* bar-*'
 * @returns {jQuery|*}                  Passed element
 */
function removeClassWildcard($element, removals) {
    if (removals.indexOf('*') === -1) {
        // Use native jQuery methods if there is no wildcard matching
        $element.removeClass(removals);
        return $element;
    }

    var patt = new RegExp('\\s' +
            removals.replace(/\*/g, '[A-Za-z0-9-_]+').split(' ').join('\\s|\\s') +
            '\\s', 'g');

    $element.each(function (i, it) {
        var cn = ' ' + it.className + ' ';
        while (patt.test(cn)) {
            cn = cn.replace(patt, ' ');
        }
        it.className = $.trim(cn);
    });

    return $element;
}

Example:


  // create some element
var $element = $('<div id="#some-element"/>')
                  .addClass('base-class has-state-active item item-75')
                  .appendTo('body');

  // remove classes with few prefixes
removeClassWildcard( $element, 'has-state-* item-*');

  // display element classes
console.log($element.attr('class'));    // >> "base-class item"
IStranger  PHP, SQL, JavaScript, Delphi. Yii
  • Reputation: 15
  • Snippets: 8
  • Revisions: 0

"Golden" rule of frontend optimization often recommends to insert all JS scripts on page end. However usualy we can't remove <script src="//jquery.js"> from page <head>, because page content can contain many onReady-handlers, for example $(function(){ ... }).

This short snippet allows move jquery.js from <head> to end of <body> without changing onReady-handlers.

Snippet:

<head>
	<script>
		// Fallback code for the jQuery inline scripts on pages:
      if (window.jQuery === undefined) {
          window.jQueryReadyHandlers = [];

          window.$ = window.jQuery = function (callback) {
              window.jQueryReadyHandlers.push(callback);
              return window.$;
          };

          window.$.ready = window.$;
      }
  	</script>
    <!-- ...some head items -->
</head>
<body>

	<!-- ...some page content -->
    
    <script> 
    	// some onReady-handlers
      $(function(){
          console.log('First callback');
      });

      jQuery(document).ready(function(){
          console.log('Second callback');
      });
    </script>
    
    <!-- ...some page content -->


	<script src="//js/jquery.min.js"></script>
    <script>
    	jQuery(window).load(function(){
        	if(window.jQueryReadyHandlers) { 
            	$.each(window.jQueryReadyHandlers, function(index,func){  
                	$(func);
                });
            }
        });
    </script>
</body>