Ashok kumar
Ashok kumar

Reputation: 542

Get the text from textarea line by line?

HTML Code

<textarea id="test"></textarea>
<button id="button_test">Ok</button>

Javascript

  $(document).ready(function()
  {
     $("#test").val("123e2oierhqwpoiefdhqwopidfhjcospid");
  });
 $("#button_test").on("click",function()
      {
      var as=document.getElementById("test").value;
      console.log(as);
      });

We can get the values from textarea line by line using val and split functions. But Is it possible to get the value from textarea line by line for very long word?.In the example i need to get the output as 123e2oierhqwpoiefdhqwo and pidfhjcospid as separate values. Jsfiddle link here

Upvotes: 5

Views: 3388

Answers (5)

Alexander Dixon
Alexander Dixon

Reputation: 874

The <textarea> element has built in functionality to control where words wrap. The cols attribute can be set (either harded coded in the HTML or set with the .attr() method using jQuery). The attribute extends the text area horizontally and it also automatically wraps text at the set value.

Example jsFiddle

$("#test").val("123e2oierhqwpoiefdhqwopidfhjcospid");
var newString = $("#test").val().toString();
var splitString = parseInt($("#test").attr("cols"), 10) + 1;
var stringArray = [];
stringArray.push(newString);
var lineOne = stringArray[0].slice(0, splitString);
var lineTwo = stringArray[0].slice(splitString);
var lineBreakString = lineOne + "\n" + lineTwo;
console.log(lineTwo);
$('#test').after("<pre>" + lineBreakString + "</pre>");

$("#test").val("123e2oierhqwpoiefdhqwopidfhjcospid");
var newString = $("#test").val().toString();
var splitString = parseInt($("#test").attr("cols"), 10) + 1;
var stringArray = [];
stringArray.push(newString);
var lineOne = stringArray[0].slice(0, splitString);
var lineTwo = stringArray[0].slice(splitString);
var lineBreakString = lineOne + "\n" + lineTwo;
$('#test').after("<pre>" + lineBreakString + "</pre>");
//console.log(lineBreakString);
pre {
  color: green;
  background: #CCC;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<textarea id="test" cols='21'></textarea>
<button id="button_test">Ok</button>

The example addresses the specific question asked. If you want to deal with larger blocks of text, you should use the .each() method and for loops to iterate over each line break.

Documentation:

.slice()

textarea

.push()

.parseInt()

.attr()

Upvotes: 0

Jax Teller
Jax Teller

Reputation: 1467

This is probly not the best way, but it works and i hope it could help you. First thing, i found the textarea allow 8px for default fontsize charactere. Exemple : Textarea with 80px => Allow line with 10 char maximum, all other are overflow on new line.

From this you can do a simple function like this :

$("#button_test").on("click",function()
{
console.clear();
var length_area = $("#test").width();
var length_value = $("#test").val().length;

var index = Math.trunc(length_area/8);

var finalstr = $("#test").val().substring(0, index) + " " + $("#test").val().substring(index);

console.log(finalstr);

});

Here the JSFiddle

Upvotes: 0

Jack jdeoel
Jack jdeoel

Reputation: 4584

Use .match(/pattern/g). As your OP ,pattern should start \w (Find a word character) and match string sequence {start,end}

$("#button_test").on("click",function()
{
  var as=document.getElementById("test").value; 
  console.log(as.match(/(\w{1,22})/g));
});

Upvotes: 1

NTL
NTL

Reputation: 1007

You can use something like this. This will insert line breaks into into the textarea.

Credits: https://stackoverflow.com/a/4722395/4645728

$(document).ready(function() {
    $("#test").val("123e2oierhqwpoiefdhqwopidfhjcospid");
});

$("#button_test").on("click", function() {
    ApplyLineBreaks("test");
    var as = document.getElementById("test").value;
    console.log(as);
});

//https://stackoverflow.com/a/4722395/4645728
function ApplyLineBreaks(strTextAreaId) {
    var oTextarea = document.getElementById(strTextAreaId);
    if (oTextarea.wrap) {
        oTextarea.setAttribute("wrap", "off");
    } else {
        oTextarea.setAttribute("wrap", "off");
        var newArea = oTextarea.cloneNode(true);
        newArea.value = oTextarea.value;
        oTextarea.parentNode.replaceChild(newArea, oTextarea);
        oTextarea = newArea;
    }

    var strRawValue = oTextarea.value;
    oTextarea.value = "";
    var nEmptyWidth = oTextarea.scrollWidth;
    var nLastWrappingIndex = -1;
    for (var i = 0; i < strRawValue.length; i++) {
        var curChar = strRawValue.charAt(i);
        if (curChar == ' ' || curChar == '-' || curChar == '+')
            nLastWrappingIndex = i;
        oTextarea.value += curChar;
        if (oTextarea.scrollWidth > nEmptyWidth) {
            var buffer = "";
            if (nLastWrappingIndex >= 0) {
                for (var j = nLastWrappingIndex + 1; j < i; j++)
                    buffer += strRawValue.charAt(j);
                nLastWrappingIndex = -1;
            }
            buffer += curChar;
            oTextarea.value = oTextarea.value.substr(0, oTextarea.value.length - buffer.length);
            oTextarea.value += "\n" + buffer;
        }
    }
    oTextarea.setAttribute("wrap", "");
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<textarea id="test"></textarea>
<button id="button_test">Ok</button>

Upvotes: 2

Hozeis
Hozeis

Reputation: 1742

If you made the textarea width fixed using css you could do this:

css

textarea { resize: vertical; }

javascript

$("#button_test").on("click",function(){
    var as=document.getElementById("test").value;
    var len = document.getElementById("test").cols;
    var chunks = [];

    for (var i = 0, charsLength = as.length; i < charsLength; i += len) {
        chunks.push(as.substring(i, i + len));
    }
    console.log(chunks);
});

Upvotes: 0

Related Questions