Remove tabs and keep spaces & line breaks
Remove tab characters and keep whitespace and line breaks. Get the total character count.
by bmarsh123
HTML
<div>
<textarea id="txtArea"></textarea>
</div>
<div>
<input type="button" id="btnRemoveSpaces" value="Remove Spaces" />
</div>
<div>
<label id="lblTotal"></label>
</div>
<div>
<label id="lblLineBreaks"></label>
</div>
CSS
div {
min-width: 100%;
margin-top: 5px;
}
textarea {
width: 100%;
min-height: 250px;
}
JavaScript
/*
* Current testing only performed in Google Chrome Version 39.0.2171.95
*/
(function ($) {
$.fn.extend({
allowTabChars: function (prevent) {
$(this).on('keydown', function(e) {
if (e.keyCode === 9) {
if (prevent === false) {
// Tab key press moves to next control
return;
} else {
// Tab key press adds a tab character to the text area/input
var $this = $(this),
value = $this.val(),
start = this.selectionStart,
end = this.selectionEnd;
$this.val(value.substring(0, start) + '\t' + value.substring(end));
// Put caret at right position again (add one for the tab)
this.selectionStart = this.selectionEnd = start + 1;
// Prevent focus loss
e.preventDefault();
}
}
});
}
});
})(jQuery);
$(function () {
// 'true' --> allow tab characters
// 'false' --> do not allow tab characters (tab key press goes to next control)
$('#txtArea').allowTabChars(true);
$('#btnRemoveSpaces').on('click', function (e) {
$('#txtArea').val($('#txtArea').val().replace(/ /g, ' ').replace(/\t/g, ''));
// Get total character count
// Line breaks are NOT counted in character count
var txtArea = $('#txtArea').val(),
lineBreaks = (txtArea.match(/\n/g) || []).length,
charCount = txtArea.length - lineBreaks;
$('#lblTotal').html('Total character count: ' + charCount + ' characters');
$('#lblLineBreaks').text(lineBreaks + ' line breaks');
$(lineBreaks).each(function () {
$('body').append($(this).val());
});
// Prevent any submissions
...