Andres SK
Andres SK

Reputation: 10982

Sanitizing a textarea value: trim white spaces in all lines

I've set the paste event to sanitize the textarea value. It already does everything I need, except one thing: trim white spaces at the beginning and end of all lines. Any ideas?

$('#q').bind('paste',function(e) {
    $.doTimeout(100,function(){
        $('#q').val($('#q').val().replace(/[@#$%\^&*=_+"'\/<>\\\|{}\[\]]/g,function(str){return '';})); //remove unwanted characters
        $('#q').val($('#q').val().replace(/[\t ]+/g,' ')); //remove extra spaces and tabs between letters 
        $('#q').val($('#q').val().replace(/\n{1,}/g,'\n\n')); //remove extra lines
        //here i need to remove white spaces at the beginning or end of each line
    });
});

ps: im using ben alman's doTimeout plugin because the paste event gets fired before the text is available.

Upvotes: 0

Views: 2582

Answers (1)

Kevin B
Kevin B

Reputation: 95066

Something like this? http://jsfiddle.net/Tentonaxe/ptGS5/

$('#q').bind('paste',function(e) {
    setTimeout(function(){
        var baseStr = $('#q').val();
        baseStr = baseStr.replace(/[@#$%\^&*=_+"'\/<>\\\|{}\[\]]/g,"");
        baseStr = baseStr.replace(/[\t ]+/g,' ');
        baseStr = baseStr.replace(/\n{1,}/g,'\n\n');
        lineArr = baseStr.split(/\n/);
        for (var i=0;i<lineArr.length;i++) {
            lineArr[i] = lineArr[i].replace(/(^ +| +$)/g,"");   
        }
        baseStr = lineArr.join("\n")
        $("#q").val(baseStr);
    },100);
});

It was easier for me to just use setTimeout than copy the doTimeout plugin into jsfiddle.

Upvotes: 1

Related Questions