Skip to content

Instantly share code, notes, and snippets.

@zx1986 zx1986/counter.js
Created Dec 3, 2015

Embed
What would you like to do?
用 JavaScript 數中文或英文字數
function if_chinese (str) {
var string_length = str.length;
var tmp = '';
if(string_length > 0) {
for(var i = 0; i < string_length; i++) {
tmp = '';
tmp = escape(str.charAt(i));
if( tmp.charAt(0) == '%') {
var cc = '';
cc = tmp.charAt(1);
if(cc =='A' || cc =='u') {
return true;
}
}
}
return false;
}
else {
return false;
}
}
function words_counter () {
var words = $("textarea.words").val().replace(/\r\n/g, "\n");
var isChinese = if_chinese(words);
if(isChinese) { var max = 70; }
else { var max = 160; }
var words_counter = words.length + (words.match(/\r/g) || []).length + (words.match(/\n/g) || []).length;
var messages_counter = Math.ceil(words_counter / max);
$("#words_counter").html(words_counter);
$("#messages_counter").html(messages_counter);
}
$("textarea.words").bind('keyup change', words_counter);
if ($("textarea.words").length) { words_counter(); }
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-1.11.3.js"></script>
<meta charset="utf-8">
<title>JS Bin</title>
</head>
<body>
<textarea class="words">
</textarea>
<p id="words_counter">
</p>
<p id="messages_counter">
</p>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.