I've implemented a JavaScript function to show users the remaining character count on a page. However, when I validate the length server-side before inserting it into a database column, the count appears to be different.
After researching online, it seems that JavaScript counts new lines/CR and other special characters differently than C#. Has anyone encountered this issue and found a workaround?
Here is the JavaScript code snippet used on the client side:
<script>
var textarea = document.getElementById('TxtComment');
window.onload = textareaLengthCheck();
function textareaLengthCheck() {
var maxChars = 4000;
var textArea = textarea.value.length;
var charactersLeft = maxChars - textArea;
var count = document.getElementById('cmt-characters-left');
count.innerHTML = "Characters left: " + charactersLeft + " of " + maxChars;
}
textarea.addEventListener('keyup', textareaLengthCheck, false);
textarea.addEventListener('keydown', textareaLengthCheck, false);
</script>
I attempted to solve the issue by adding the following line of code, but unfortunately, it made the problem worse:
var textArea = textarea.value.replace(/(\r\n|\n|\r)/g, "").length;