Link to home
Start Free TrialLog in
Avatar of Chris24
Chris24

asked on

Remove whitespace and replace all chr(13) and chr(10)

Hi all....

I need a script that will, onKeyUp, remove/prevent carriage returns 'chr(13)', line feeds 'chr(10), and multiple spaces in a text area. When a user is typing into the text area and hits Return, it prevents it. If the user presses space multiple times, it only allows a single space.

I have the following from a few scripts I found on EE (I believe part is ZVonko's script) but I don't understand RegExp well enough to edit it to do what I need it to do. It seems to handle the carriage returns well but prevents any spaces from being entered.

<SCRIPT LANGUAGE="JavaScript">
function removeChar(input) {
var output = "";
for (var i = 0; i < input.length; i++) {
if ((input.charCodeAt(i) == 13) && (input.charCodeAt(i + 1) == 10)) {
i++;
output += " ";
} else {
output += input.charAt(i);
   }
}
return output;
}

String.prototype.fullTrim = function()
{
   return this.replace(/\s+/g," ").replace(/^\s*([\s\S]*\S+)\s*$|^\s*$/,"$1");
}
</script>

<form>
<textarea name='txtUserData' rows='8' cols='50' onKeyUp="removeChar(this.form.txtUserData.value);this.value=this.value.fullTrim()"></textarea>
</form>

Thanks in advance,
Chris24
ASKER CERTIFIED SOLUTION
Avatar of devic
devic
Flag of Germany image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Chris24
Chris24

ASKER

Perfect!! Thank you.

I just created a function from it.

function funcFormat(theValue) {
      theValue.value=theValue.value.replace(/ {2,}/g,' ').replace(/[\n\r]*/g,'');
}

And changed the onKeyUp event to: onKeyUp="return funcFormat(this)"

I greatly appreciate it!

Thank you
you are welcome!