Replace line-breaks by spaces using javascript

compcobalt picture compcobalt · Oct 28, 2011 · Viewed 7.5k times · Source

I want to see if it's possible to block the enter key and replace it with a space. I'm also using form validation to only allow letters, numbers and some other specific characters like the dollar sign,minus, and period and so on.

Here is that code, I would like to see if I can combine them into one and be able to check for the validation and replace the key press with a space all in one code/call.

<script type="text/javascript">
function ValidateForm(form)
{
var str
str=document.getElementById('limitedtextarea').value
str=str.replace(/[^A-Za-z0-9.-:/$ ]/g, "");
document.getElementById('limitedtextarea').value=str
//return true;

} 
</script>

<FORM action="sms_SendMessage.asp" method=post onsubmit="javascript:return ValidateForm(this)" target=_blank>

Thanks for the help...

Answer

Leo picture Leo · Oct 28, 2011

In javascript, the line-break character is represented by \n. You could replace them by spaces in your validation function like this :

function ValidateForm(form)
{
    var str
    str=document.getElementById('limitedtextarea').value
    str=str.replace(/[^A-Za-z0-9.-:/$ ]/g, "");
    str=str.replace(/\n/g, " ");
    document.getElementById('limitedtextarea').value=str
    //return true;

}