Skip to content

Instantly share code, notes, and snippets.

@megazalrock
Created February 18, 2014 15:24
Show Gist options
  • Save megazalrock/9073083 to your computer and use it in GitHub Desktop.
Save megazalrock/9073083 to your computer and use it in GitHub Desktop.
ランダム文字列の取得(日本語対応)
var RndText = function(){
this.strCodes = {
ja : [
{ //hiragana
start: 0x3041,
end: 0x309f
},
{ //katakana
start: 0x30a0,
end: 0x30ff
},
{ //cjk
start: 0x4e00,
end: 0x9fcf
}
],
en: {
start: 0x021,
end: 0x07E
}
};
};
RndText.prototype.checkType = function(type, obj){
var clas = Object.prototype.toString.call(obj).slice(8, -1);
return obj !== undefined && obj !== null && clas === type;
};
RndText.prototype.getString = function(langCode){
langCode = langCode || 'en';
var lang = this.strCodes[langCode], result = [];
if(this.checkType('Array', lang)){
var i = 0, length = lang.length;
for(; i < length; i += 1){
result.push( String.fromCharCode( Math.floor( Math.random() * (lang[i].end - lang[i].start + 1 ) + lang[i].start ) ) );
}
result = result[ Math.floor(Math.random() * result.length)].replace(/\s/g, '');
}else{
result = String.fromCharCode( Math.floor( Math.random() * ( lang.end - lang.start + 1 ) ) );
}
return result.toString();
};
RndText.prototype.getStrings = function(langCode, length){
length = length || 1;
var i = 0, result = [];
for(; i < length; i += 1){
result.push(this.getString(langCode));
}
return result.join('');
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment