Created
December 3, 2015 08:16
-
-
Save zx1986/deba2c24fac260a1fc25 to your computer and use it in GitHub Desktop.
用 JavaScript 數中文或英文字數
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(); } |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!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