diff --git a/js/maxlength.js b/js/maxlength.js
index a590fac..baaa3ef 100644
--- a/js/maxlength.js
+++ b/js/maxlength.js
@@ -137,7 +137,7 @@
          commentsAndPhpTags = /<!--[\s\S]*?-->|<\?(?:php)?[\s\S]*?\?>/gi;
      return input.replace(commentsAndPhpTags, '').replace(tags, function($0, $1){
          return allowed.indexOf('<' + $1.toLowerCase() + '>') > -1 ? $0 : '';
-     });
+     }).replace(/<[^>]*>/g, '').replace(/\r\n/g, '').replace(/\s+/g, ' ').replace(/&\w+;/g ,'X').replace(/^\s*/g, '').replace(/\s*$/g, '');
   };
 
   /**
diff --git a/maxlength.module b/maxlength.module
index 2473fbb..97ad7c4 100644
--- a/maxlength.module
+++ b/maxlength.module
@@ -171,7 +171,7 @@ function maxlength_validate_input(&$element, &$form_state) {
   if (isset($element['#attributes']['maxlength']) && isset($element['#value'])) {
     // Compute the length of the text, without counting the tags, and consider
     // the "enter" characters as only one character.
+    // And strip whitespace from the beginning and end of a string
-    $value = filter_xss(str_replace(array("\r\n", '&nbsp;'), array(' ', ' '), $element['#value']), array());
+    $value = trim(htmlspecialchars_decode(filter_xss(str_replace(array("\r\n", '&nbsp;'), array('', ' '), $element['#value']), array())));
     if (drupal_strlen($value) > $element['#attributes']['maxlength']) {
       form_error($element, t('!name cannot be longer than %max characters but is currently %length characters long.', array('!name' => empty($element['#title']) ? $element['#parents'][0] : $element['#title'], '%max' => $element['#attributes']['maxlength'], '%length' => drupal_strlen($value))));
     }
