Skip to content

Instantly share code, notes, and snippets.

@bzz0217
Created May 16, 2016 15:47
Show Gist options
  • Save bzz0217/c1f34aca2e2a33eae0669e743e5fcde8 to your computer and use it in GitHub Desktop.
Save bzz0217/c1f34aca2e2a33eae0669e743e5fcde8 to your computer and use it in GitHub Desktop.
10文字で丸める / 文字数を測定
<!DOCTYPE html>
<html>
<head>
<title>文字列を丸める</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="https://code.jquery.com/jquery-2.2.3.min.js" integrity="sha256-a23g1Nt4dtEYOj7bR+vTu7+T8VP13humZFBJNIYoEJo=" crossorigin="anonymous"></script>
<script src="./jquery.ry.js"></script>
<script>
/*
* 文字数チェック(全角2, 半角1で集計)
* サロゲートベア対応(4バイト対応)
*
* @param string str 文字列
* @return int len 文字数
*/
var charcount = function (str) {
len = 0;
//サロゲートベアの文字数を計測(最後でサロゲートベアの文字数分引く)
var surrogate_num = str.split( /[\uD800-\uDBFF][\uDC00-\uDFFF]/g ).length - 1;
if (surrogate_num>0){
//全角2半角1である為、サロゲートベアを全角に合わせる
surrogate_num = surrogate_num * 2;
}
//改行を1文字分とする為「あ」に置換します
str = str.replace(/\n/g, "あ");
str = escape(str);
for (i=0;i<str.length;i++,len++) {
if (str.charAt(i) == "%") {
if (str.charAt(++i) == "u") {
i += 3;
len++;
}
i++;
}
}
return len - surrogate_num;
}
$(function(){
$('textarea.text').on('keyup change', function(){
//テキストエリア入力
var text = $('.text').val();
$(".strwidth").text(text);
//文字数チェック
var str_count = charcount(text);
str_count = str_count / 2;
$('.str_count').text(str_count);
/*
* jquery.ry.js
* ・10文字で丸める
* ・サロゲートベア非対応
*/
$(".strwidth").ry({
size: 10
});
});
});
</script>
<style>
pre{
width:200px;
height:300px;
border:1px solid #808080;
padding:5px;
}
.content{
width:200px;
}
.strwidth{
font-size:18px;
font-weight: 800;
color: darkslategrey;
width:200px;
height:100px;
}
.text{
width:200px;
height:100px;
margin-top:15px;
}
.count_area{
float:right;
}
.str_count{
font-weight:800;
color:#c0392b;
font-size:18px;
}
label{
font-weight:800;
}
.output{
margin-top:30px;
}
</style>
</head>
<body>
<div class='content'>
<label>テキスト入力:</label>
<textarea class='text'></textarea>
<div class='count_area'>
<span class='str_count'>0</span>
<span>文字</span>
</div>
<div class='output'>
<label>出力:</label>
<pre class='strwidth'></pre>
</div>
</div>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment