2016-08-01 189 views
0

首先,我尝试了我在这里找到的所有可能的解决方案或Google,但似乎没有人为我工作。使用jQuery从textarea中删除空行

要清楚,我需要删除文本区域中的每个空行。 这是我迄今所做的:

<textarea name="text" class="form-control" rows="14" id="text" placeholder="Here goes our query" ></textarea> 


$(document).ready(function() { 
    $('#text').focusout(function() { 
     var text = $('#text').val(); 

     text.replace(/(\r\n|\n|\r)/gm,""); 

     alert('done'); 
    }); 
}); 

我得到最终成功的警报,但这些空行仍然存在。正则表达式正确吗? 我对js的知识并不大,所以我需要帮助:(

+1

参见[* JavaScript的:*如何使用正则表达式从字符串中删除空行?(HTTP://计算器.com/questions/16369642/javascript-how-to-use-a-regular-expression-to-remove-blank-lines-from-a-string)and [*无法用Javascript代替textarea中的空行换行方法*](http://stackoverflow.com/questions/13205169/cant-remove-empty-line-break-in-textarea-with-javascript-replace-method)。另外,[* jquery text()。replace('','')not working *](http://stackoverflow.com/questions/28025944/jquery-text-replace-not-working)。 –

回答

3

http://www.w3schools.com/jsref/jsref_replace.asp

的replace()方法搜索指定的值,或正则表达式的字符串,并返回一个新字符串其中指定的值替换。

所以你实际上并没有改变textarea的价值。

您可以使用

$(document).ready(function() { 
    $('#text').focusout(function() { 
     var text = $('#text').val(); 
     text = text.replace(/(?:(?:\r\n|\r|\n)\s*){2}/gm, ""); 
     $(this).val(text); 
    }); 
}); 

The regex is from here.

0

你可以尝试这样的:

$(document).ready(function() { 
    $('#text').focusout(function() { 
     var text = $('#text').val(); 

     var modifiedtext=text.replace(/ /g, ""); 
     $(this).val(modifiedtext); 
     alert('done'); 

    }); 
}); 
+0

这两种解决方案都有一个窍门。谢谢。 :-) – fugitive