文字の前後の文字種を判定する。
参考:javascriptのmatchで質問です。 - OKWave
OKWaveに回答してからの変更点。
<script>
"use strict";
(function(window, document, undefined){
function $(id, val){
var el = document.getElementById(id);
if( val!==undefined) {
el.value=val;
}
return el.value;
}
var _judges=["", "空白", "アルファベット", "ひらがな"];
function isFirst(c, text){
return (new RegExp("^"+c)).test(text)? _judges.indexOf("空白"): 0;
}
function isLast(c, text){
return (new RegExp(c+"$")).test(text)? _judges.indexOf("空白"): 0;
}
function isSpace(c){
return ( /[ \s]/.test(c) )? _judges.indexOf("空白") : 0;
}
function isAlpha(c){
return ( /[a-zA-Z]/.test(c) )? _judges.indexOf("アルファベット") : 0;
}
function isHiragana(c){
return ( /[あ-んを]/.test(c) )? _judges.indexOf("ひらがな") : 0;
}
function getCharType(c){
return isSpace(c) || isAlpha(c) || isHiragana(c) || 0;
}
function judge(){
var c = $('ipt_c'),
text = $('ipt_text'),
result = '';
var re = text.match( (new RegExp("(.?)"+c+"(.?)")) );
if( re ){
var before = _judges[ isFirst(c, text) || getCharType(re[1]) ],
after = _judges[ isLast(c, text) || getCharType(re[2]) ];
if( before === after ){
result += before + "です。";
}else{
result += "前が" + before + "で後ろが" + after + "です。";
}
}
$('ipt_out', result);
}
window.$ = $;
window.judge = judge;
})(this, document, void(0));
</script>