Replace line-breaks by spaces using javascript

2019-07-07 09:09发布

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...

2条回答
Evening l夕情丶
2楼-- · 2019-07-07 09:34

If you remove the onsubmit and do not have a submit button, typing enter will not submit it.

<body>
    <form>
        <textarea></textarea>
    </form>
<script>
(function(){
    var txt = document.getElementsByTagName('TEXTAREA')[0];
    txt.onkeypress = function(ev){
        ev = ev || window.event;
        if ( ev.keyCode === 13 ){
            if (window.event) {
                window.event.returnValue = false;
            }
            if (ev && ev.preventDefault) {
                ev.preventDefault();
            }
            txt.value += ' ';
        }
    };
})();
</script>
</body>
查看更多
萌系小妹纸
3楼-- · 2019-07-07 09:37

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;

}
查看更多
登录 后发表回答