javascript - How to get content of each line on textarea - Stack Overflow

If textarea display line 1 ![Screen Shot 2025-02-21 at 17.32.49.png] and line 2 is (http:localhost:90

If textarea display line 1 ![Screen Shot 2025-02-21 at 17.32.49.png] and line 2 is (http://localhost:9001/article/680x_4a9d1136-fafb-40dc-8a47-72ca0b24bf46.png), how can I get content of textarea by array of line content. That mean from image I expect I can get array like below

["![Screen Shot 2025-02-21 at 17.32.49.png]", 
 "(http://localhost:9001/article/680x_4a9d1136-fafb-40dc-8a47-72ca0b24bf46.png)"]

function splitTextarea() {
  const textarea = document.getElementById("myTextarea");
  const text = textarea.value;

  // Step 1: Split by hard line breaks (`\n`)
  const lines = text.split("\n");
  const renderedRows = []
  // Step 2: For each paragraph, split into rows based on textarea width
  // const rowsArray = [];
  const tempElement = document.createElement("div");
  tempElement.style.position = "absolute";
  // tempElement.style.visibility = "hidden";
  tempElement.style.overflowWrap = "break-word";
  tempElement.style.whiteSpace = "pre-wrap"; // Preserve spaces and line breaks
  tempElement.style.width = `${textarea.clientWidth}px`; // Match textarea width
  tempElement.style.fontFamily = getComputedStyle(textarea).fontFamily; // Match font
  tempElement.style.fontSize = getComputedStyle(textarea).fontSize; // Match font size
  tempElement.style.lineHeight = getComputedStyle(textarea).lineHeight; // Match line height
  // tempElement.style.padding = getComputedStyle(textarea).padding; // Match padding
  // tempElement.style.boxSizing = "border-box"; // Match box sizing
  document.body.appendChild(tempElement);

  lines.forEach(line => {
    if (line === '') {
      // Handle blank lines
      renderedRows.push('');
    } else {
      let start = 0;
      while (start < line.length) {
        let end = start;
        while (end < line.length) {
          const text = line.slice(start, end);
          tempElement.textContent = line.slice(start, end);
          const computedStyle = window.getComputedStyle(tempElement);
          const height = computedStyle.height;
          const heightInt = parseInt(height, 10);
          // if (text === "2全国各地から厳選された有名焼き芋店やおいもスイーツの専門店が集結し、素材にこだわった極上の焼き芋や多彩な") {
          //   console.log('heightInt', heightInt)
          // }
          console.log(text, heightInt)
          if (heightInt > 19) {
            // console.log('end,', end)
            end = end - 1
            break;
          }
          end++;
        }
        console.log("line", line.slice(start, end))
        renderedRows.push(line.slice(start, end));

        start = end;
      }
    }
  });

  // Clean up
  // document.body.removeChild(tempElement);

  console.log("Rows Array:", renderedRows);
  return renderedRows;
}
<textarea id="myTextarea" style="width: 700px; height: 300px; overflow-y: scroll;">
![Screen Shot 2025-02-21 at 17.32.49.png](http://localhost:9001/article/680x_4a9d1136-fafb-40dc-8a47-72ca0b24bf46.png)
</textarea>
<div id="textForm"></div>
<button onclick="splitTextarea()">Split Textarea</button>

If textarea display line 1 ![Screen Shot 2025-02-21 at 17.32.49.png] and line 2 is (http://localhost:9001/article/680x_4a9d1136-fafb-40dc-8a47-72ca0b24bf46.png), how can I get content of textarea by array of line content. That mean from image I expect I can get array like below

["![Screen Shot 2025-02-21 at 17.32.49.png]", 
 "(http://localhost:9001/article/680x_4a9d1136-fafb-40dc-8a47-72ca0b24bf46.png)"]

function splitTextarea() {
  const textarea = document.getElementById("myTextarea");
  const text = textarea.value;

  // Step 1: Split by hard line breaks (`\n`)
  const lines = text.split("\n");
  const renderedRows = []
  // Step 2: For each paragraph, split into rows based on textarea width
  // const rowsArray = [];
  const tempElement = document.createElement("div");
  tempElement.style.position = "absolute";
  // tempElement.style.visibility = "hidden";
  tempElement.style.overflowWrap = "break-word";
  tempElement.style.whiteSpace = "pre-wrap"; // Preserve spaces and line breaks
  tempElement.style.width = `${textarea.clientWidth}px`; // Match textarea width
  tempElement.style.fontFamily = getComputedStyle(textarea).fontFamily; // Match font
  tempElement.style.fontSize = getComputedStyle(textarea).fontSize; // Match font size
  tempElement.style.lineHeight = getComputedStyle(textarea).lineHeight; // Match line height
  // tempElement.style.padding = getComputedStyle(textarea).padding; // Match padding
  // tempElement.style.boxSizing = "border-box"; // Match box sizing
  document.body.appendChild(tempElement);

  lines.forEach(line => {
    if (line === '') {
      // Handle blank lines
      renderedRows.push('');
    } else {
      let start = 0;
      while (start < line.length) {
        let end = start;
        while (end < line.length) {
          const text = line.slice(start, end);
          tempElement.textContent = line.slice(start, end);
          const computedStyle = window.getComputedStyle(tempElement);
          const height = computedStyle.height;
          const heightInt = parseInt(height, 10);
          // if (text === "2全国各地から厳選された有名焼き芋店やおいもスイーツの専門店が集結し、素材にこだわった極上の焼き芋や多彩な") {
          //   console.log('heightInt', heightInt)
          // }
          console.log(text, heightInt)
          if (heightInt > 19) {
            // console.log('end,', end)
            end = end - 1
            break;
          }
          end++;
        }
        console.log("line", line.slice(start, end))
        renderedRows.push(line.slice(start, end));

        start = end;
      }
    }
  });

  // Clean up
  // document.body.removeChild(tempElement);

  console.log("Rows Array:", renderedRows);
  return renderedRows;
}
<textarea id="myTextarea" style="width: 700px; height: 300px; overflow-y: scroll;">
![Screen Shot 2025-02-21 at 17.32.49.png](http://localhost:9001/article/680x_4a9d1136-fafb-40dc-8a47-72ca0b24bf46.png)
</textarea>
<div id="textForm"></div>
<button onclick="splitTextarea()">Split Textarea</button>

Share Improve this question edited Feb 23 at 15:05 mplungjan 179k28 gold badges182 silver badges240 bronze badges asked Feb 23 at 13:36 binh truongbinh truong 11 bronze badge 1
  • code loops forever – mplungjan Commented Feb 23 at 15:18
Add a comment  | 

3 Answers 3

Reset to default 0
  1. You text is not multiline and has no such \n. It's just text-wrapped. (Well, it has one \n at the end, but I don't see how this is related to your question)
  2. Your textarea value resembles a Markdown Image format
  3. You could use Regex to retrieve the desired parts:

const getMDImages = (str) => {
  const parts = str.matchAll(/!\[(?<alt>[^\]]+)\]\((?<filename>[^"\)]+)( "(?<title>[^"]+)")?\)/gm); 
  return [...parts].map((part) => part.groups);
};

console.log(getMDImages(document.querySelector("#myTextarea").value));
<textarea id="myTextarea" style="width: 700px; height: 130px;"># Some title
Here's my image:  
![Screen Shot 2025-02-21 at 17.32.49.png](http://localhost:9001/article/xbla.png)  
## Subtitle 
- Some
- List
![Nice screen](screen.png "My screen title")  
</textarea>

Just grab the text and split by \n:

function splitTextarea() {
  const text = document.getElementById("myTextarea").value;
  const lines = text.split("\n"); // Easy way to get each line
  console.log(lines);
  return lines;
}

There is no need for all that extra DOM stuff unless you're handling word wrapping inside the textarea. If so, you'd need a more complex approach using canvas or measuring text width properly.

You can simplify your approach by directly splitting the textarea content by \n and storing each line as an element in an array. Since your textarea contains a Markdown-style image link, you want to ensure that it doesn't get split incorrectly. Here's a cleaner way to achieve this:

Solution Modify your JavaScript function as follows:

function splitTextarea() {
    const textarea = document.getElementById("myTextarea");
    const text = textarea.value;

    // Split text by new lines to get an array of lines
    const linesArray = text.split("\n");

    console.log("Lines Array:", linesArray);
    return linesArray; }

Expected Output For your given textarea content:

![Screen Shot 2025-02-21 at 17.32.49.png](http://localhost:9001/article/680x_4a9d1136-fafb-40dc-8a47-72ca0b24bf46.png)]

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745153157a4613957.html

相关推荐

  • javascript - How to get content of each line on textarea - Stack Overflow

    If textarea display line 1 ![Screen Shot 2025-02-21 at 17.32.49.png] and line 2 is (http:localhost:90

    7小时前
    20

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信