admin管理员组

文章数量:1394186

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

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

Share Improve this question asked Jun 29, 2016 at 14:35 Ashok kumarAshok kumar 5421 gold badge5 silver badges22 bronze badges 3
  • 1 You could use something like slice – jhhayashi Commented Jun 29, 2016 at 14:39
  • You would use the native <textarea> parameters cols attribute to set the number of columns so you have an idea of where this will break. Then, you would let JavaScript do the rest of the work with methods you mentioned (.split()). – Alexander Dixon Commented Jun 29, 2016 at 14:41
  • Are you able to set a fixed number of columns on the text area, or does it have to be resizeable by the user? – Rose Kunkel Commented Jun 29, 2016 at 14:57
Add a ment  | 

5 Answers 5

Reset to default 2

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

Credits: https://stackoverflow./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./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./ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<textarea id="test"></textarea>
<button id="button_test">Ok</button>

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));
});

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);
});

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

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./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()

本文标签: javascriptGet the text from textarea line by lineStack Overflow