JavaScript のちょっとした関数 (メモ)
あると便利かなあと思ったやつをネットで検索して自分向けにちょっと変えた。
URL のパラメータを取得(してオブジェクトに格納)
URL をパラメータで渡せるようにした(参照元)。
/**
* parse query string for given URL or current location
* @see http://snipplr.com/view/15638/query-string-parsing-in-javascript/
* @param {string} URL
* @return {object} Parameters (key-value)
*/
var parseQueryString = function(sUrl){
var oParams = {},
sQuery = sUrl ? sUrl.split("?")[1] : window.location.search.substring(1);
if (sQuery) {
sQuery.replace(/([^?=&]+)(=([^&]*))?/g,
function( $0, $1, $2, $3 ){
oParams[ $1 ] = $3;
}
);
}
return oParams;
};
マルチバイト文字を 2 byte と数えてカットする SubStr みたいな関数
参照元は String オブジェクトを拡張してたのを ただの関数にした。
/**
* return true if given character is multibyte. if the given argument
* is more than one character, it uses the first character of the string
* @see http://oshiete1.watch.impress.co.jp/qa5076682.html
* @param {string} Char that can be get by String.charAt()
* @return {boolean} true if it's multibyte
*/
var isMultiByte = function(sChar){
var sCharCode = sChar.charCodeAt(0);
// Range of single byte chars
// Unicode : 0x0 〜 0x80, 0xf8f0, 0xff61 〜 0xff9f, 0xf8f1 〜 0xf8f3
if ( (sCharCode >= 0x0 && sCharCode <= 0x80)
|| (sCharCode == 0xf8f0)
|| (sCharCode >= 0xff61 && sCharCode <= 0xff9f)
|| (sCharCode >= 0xf8f1 && sCharCode <= 0xf8f3) ) {
return false;
} else {
return true;
}
};
/**
* custom substr function that counts multi-byte character as 2 bytes.
* @require isMultiByte()
* @see http://oshiete1.watch.impress.co.jp/qa5076682.html
* @param {string} String to be extracted
* @param {number} Index where to start the extraction
* @param {number} Length (optional) number of characters to extract
* @return {string} Extracted text
*/
var doubleByteSubStr = function(sString, nIndex, nLength){
// find start index by byte
for (var i=0, len=0; len < nIndex; i++) {
len = isMultiByte(sString.charAt(i)) ? len+2 : len+1;
}
var nIndexBytes = i;
// find length for substr by byte
len = 0;
while(nLength > len) {
len = isMultiByte(sString.charAt(i)) ? len+2 : len+1;
i++;
}
var nLengthBytes = i - nIndexBytes,
sExtracted = sString.substr(nIndexBytes, nLengthBytes);
return sExtracted;
};