I’m having a problem with preserving tab characters when reading the value of a textarea.
I’m adding the tabs as follows:
$("#code-editor").keydown(function (e) {
if (e.keyCode === 9) { // tab was pressed
// get caret position/selection
var start = this.selectionStart;
var end = this.selectionEnd;
var $this = $(this);
var value = $this.val();
// set textarea value to: text before caret + tab + text after caret
$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 the focus lose
e.preventDefault();
}
});
The tabs are inserted correctly and are displayed in the textarea as expected.
The problem occurs when I then read the value of the textrea and try to replace to tab characters with html formatting.
$("#code-editor").keyup(function (e) {
var value = $(this).val();
//Do formatting
var lines = value.split("\n");
var newvalue = "";
for (var i = 0; i < lines.length; i++) {
lines[i].replace(/\t/g, "<span style='padding-left:3em'></span>");
lines[i] += "<br />";
newvalue += lines[i];
}
$('#editor-displayarea').html(newvalue);
});
I have discovered that the tabs do not seem to be preserved when reading from textarea.
Is there a way around this or have I taken the wrong approach?
Thanks.
Update:
I have tried using a few variations on the regular expression as stated in the comment below but to no avail.
You are not storing the value when you replace the tabs. Try something like this (I would leave the
in the span as well):