<html>
<head>
<title> New Document </title>
<script language="javascript">
function fnEscape(p_str) {
document.getElementById("str_1").value = escape(p_str);
alertLength(p_str);
}
function fnUnEscape(p_str) {
document.getElementById("str_1").value = unescape(p_str);
}
function alertLength(str) {
alert(
str.length+
(escape(str)).match(/%u/g).length*2
);
//(escape(str)+"%u").match(/%u/g).length*3
}
function BAK_alertLength(str) {
// alert(str.length+(escape(str)+"%u").match(/%u/g).length-1);
alert((escape(str)+"%u").match(/%u/g).length);
}
function testMatch() {
var str="The rain in SPAIN stays mainly in the plain";
var patt1=/ain/gi;
alert(str.match(patt1));
}
</script>
</head>
<body>
<form name="frm">
변경전 : <input type="text" name="str" id="str" size="50" />
변경후 : <input type="text" name="str_1" id="str_1" size="50" />
<input type="button" value="escape" onclick="fnEscape(frm.str.value);" />
<input type="button" value="unescape" onclick="fnUnEscape(frm.str.value);" />
<input type="button" value="testMatch" onclick="testMatch(); return false;" />
</form>
</body>
자바스크립트에서 escape로 인코딩하면 비영어권 문자들은 %u가 붙은 형태로 인코딩 되는듯 하다.
이런 형태로 출력이 된다.
%u가 붙는걸 이용하여 1byte 문자인지 2byte 문자인지 구별한다.
이걸이용해서 한글인지 영문인지 구별하는 스크립트이다.
<script type=
"text/javascript"
>
function smsByteChk(content)
{
var temp_str = content.value;
var remain = document.getElementById(
"sms_remain"
);
remain.value =
80
- getByte(temp_str);
if
(remain.value <
0
)
{
alert(
80
+
"Bytes를 초과할 수 없습니다."
);
while
(remain.value <
0
)
{
temp_str = temp_str.substring(
0
, temp_str.length-
1
);
content.value = temp_str;
remain.value =
80
- getByte(temp_str);
}
content.focus();
}
}
function getByte(str)
{
var resultSize =
0
;
if
(str ==
null
)
{
return
0
;
}
for
(var i=
0
; i<str.length; i++)
{
var c = escape(str.charAt(i));
if
(c.length ==
1
)
{
resultSize ++;
}
else
if
(c.indexOf(
"%u"
) != -
1
)
{
resultSize +=
2
;
}
else
{
resultSize ++;
}
}
return
resultSize;
}
</script>
<form name=
"frm"
>
<table>
<tr>
<td>
<input type=
"text"
name=
"sms_remain"
style=
"width:15px; border:2px dotted #00f"
maxLength=
"2"
value=
"80"
readonly>Bytes 남음
</td>
</tr>
<tr>
<td>
<textarea name=
"smscontent"
rows=
"8"
cols=
"16"
onkeyup=
"smsByteChk(this);"
onkeydown=
"smsByteChk(this);"
></textarea>
</td>
</tr>
</table>