Skip to content

Instantly share code, notes, and snippets.

@ka215
Created June 2, 2016 07:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ka215/370ee9f95c038fcb2defdc7691d83c9e to your computer and use it in GitHub Desktop.
Save ka215/370ee9f95c038fcb2defdc7691d83c9e to your computer and use it in GitHub Desktop.
JavaScriptのすぐ使える7つのユーティリティ関数 ref: http://qiita.com/ka215/items/d059a78e29adef3978b5
/**
* Return as an object by parsing the query string of the current URL
*/
$.QueryString = (function(queries) {
if ('' === queries) { return {}; }
var results = {};
for (var i=0; i<queries.length; ++i) {
var param = queries[i].split('=');
if (param.length !== 2) { continue; }
results[param[0]] = decodeURIComponent(param[1].replace(/\+/g, ' '));
}
return results;
})(window.location.search.substr(1).split('&'));
/**
* Convert unit from em to pixels
*
* @param int em [optional]
*/
$.em2pxl = function(em) {
if (em === undefined) { em = 1; }
var div = $('<div style="width:'+em+'em;"></div>').appendTo('body');
var pixel = div.width();
div.remove();
return pixel;
};
var str = '三国志の人物・彭𣴎の「𣴎」の字は4バイト文字だ';
console.info([ str.substr(0, 9), $.mb_substr(str, 0, 9) ]);
//=> [ '三国志の人物・彭�', '三国志の人物・彭𣴎' ]
/**
* Strip tags from specified strings
*/
$.strip_tags = function( str, allowed ) {
allowed = ( ( ( allowed || '' ) + '' ).toLowerCase().match(/<[a-z][a-z0-9]*>/g) || []).join('');
var tags = /<\/?([a-z][a-z0-9]*)\b[^>]*>/gi, commentsAndPhpTags = /<!--[\s\S]*?-->|<\?(?:php)?[\s\S]*?\?>/gi;
return str.replace( commentsAndPhpTags, '' ).replace( tags, function ($0, $1) {
return allowed.indexOf('<' + $1.toLowerCase() + '>') > -1 ? $0 : '';
});
};
var mixedStr = '<address><strong>Full Name</strong><br><a href="mailto:#">first.last@example.com</a></address>';
console.info( $.strip_tags(mixedStr) );
//=> Full Namefirst.last@example.com
console.info( $.strip_tags(mixedStr, '<a><br>') );
//=> Full Name<br><a href="mailto:#">first.last@example.com</a>
/**
* Survey the width of strings
*
* @param string str
* @param bool stripTags [optional]
*/
$.strWidth = function(str) {
if ('' === arguments[0]) { return 0; }
var ruler = $('<span style="visibility:hidden;position:absolute;white-space:nowrap;"></span>').appendTo('body');
var width;
if (arguments[1] !== undefined && arguments[1]) {
str = $('<div/>').html(str).text();
}
width = ruler.text(str).get(0).offsetWidth;
ruler.remove();
return width;
};
// 等幅フォント
$('body').css({ fontFamily: 'monospace' });
console.info([ $.strWidth('abc'), $.strWidth('abc'), $.strWidth('ABC'), $.strWidth('ABC') ]);
//=> [ 20, 39, 20, 39 ]
// 可変幅フォント
$('body').css({ fontFamily: 'sans-serif' });
console.info([ $.strWidth('abc'), $.strWidth('abc'), $.strWidth('ABC'), $.strWidth('ABC') ]);
//=> [ 24, 28, 31, 36 ]
/**
* Survey the size of image
*
* @param string src [optional]
*/
$.imageSize = function(src) {
var imgSize = { w: 0, h: 0 };
var img = new Image();
img.src = src;
imgSize.w = img.width;
imgSize.h = img.height;
return imgSize;
};
var imgSize = $.imageSize( $('img').attr('src') );
$('img').attr( 'width', imgSize.w/2 ).attr( 'height', imgSize.h/2 );
/**
* Perform mutual conversion between the actual strings and the html entity
*
* @param string str [required]
* @param string proc [optional] "decode" (is default) or "encode"
*/
$.htmlEntities = function(str, proc) {
if ( 'encode' === proc ) {
var buffer = [];
for ( var i=str.length-1; i>=0; i-- ) {
buffer.unshift( ['&#', str[i].charCodeAt(), ';'].join('') );
}
return buffer.join('');
} else {
return str.replace( /&#(\d+);/g, function( match, dec ) {
return String.fromCharCode( dec );
});
}
};
console.info( $.htmlEntities( '<em>強調文字</em>', 'encode' ) );
//=> &#60;&#101;&#109;&#62;&#24375;&#35519;&#25991;&#23383;&#60;&#47;&#101;&#109;&#62;
console.info( $.htmlEntities('&#60;&#101;&#109;&#62;&#24375;&#35519;&#25991;&#23383;&#60;&#47;&#101;&#109;&#62;') );
//=> <em>強調文字</em>
/**
* Functions supported multibyte string
*/
$.isSurrogatePear = function( upper, lower ) {
return 0xD800 <= upper && upper <= 0xDBFF && 0xDC00 <= lower && lower <= 0xDFFF;
};
$.mb_strlen = function( str ) {
var ret = 0;
for (var i = 0; i < str.length; i++,ret++) {
var upper = str.charCodeAt(i);
var lower = str.length > (i + 1) ? str.charCodeAt(i + 1) : 0;
if ( $.isSurrogatePear( upper, lower ) ) { i++; }
}
return ret;
};
$.mb_substr = function( str, begin, end ) {
var ret = '';
for (var i = 0, len = 0; i < str.length; i++, len++) {
var upper = str.charCodeAt(i);
var lower = str.length > (i + 1) ? str.charCodeAt(i + 1) : 0;
var s = '';
if( $.isSurrogatePear( upper, lower ) ) {
i++;
s = String.fromCharCode( upper, lower );
} else {
s = String.fromCharCode( upper );
}
if ( begin <= len && len < end ) { ret += s; }
}
return ret;
};
var str = '三国志の人物・彭𣴎の「𣴎」の字は4バイト文字だ'; //:23文字
console.info([ str.length, $.mb_strlen(str) ]);
//=> [ 25, 23 ]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment