簡體   English   中英

JavaScript 在具有 HTML 標簽的字符串中每第 12 個字符后添加一個換行符

[英]JavaScript add a line break after every 12th character in a string which has HTML tags

我有一個字符串,它是許多小字符串的組合,包裹在 HTML 標簽周圍。 目標是在不包括標簽的每 12 個字符后添加一個換行符。

'<span>This is a text.</span><span>Lets go for the walk now.</span>'

'<span>This is a te\nxt.</span><span>Lets go f\nor the walk\n now.</span>'

我嘗試過的是忽略並獲取標簽之間的值。

    let messageString = '<span>This is a text.</span><span>Lets go for the walk now.</span>';
    messageString.match(/(?<=<span>).*?(?=<\/span>)/g).forEach((s) => {
        messageString = messageString.replace(s, s.replace(/.{12}/g, '$&\n'));
  });

但是我從這里得到錯誤的 output。 我知道我在此處選擇標簽之間的文本,因此無法計數到 12。 所以我應該有一個計數器或其他東西來循環直到達到計數 12 然后添加一個換行符。 只是在想是否有更簡單的方法來做到這一點。

您需要遍歷節點樹,並在沿途遇到文本節點時迭代文本內容的每個代碼點,每次計數達到 12 時插入一個換行符。這是一個功能示例:

 function insertStringEveryNCodePoints (node, frequency, str) { const stack = [node]; let count = 0; while (stack.length > 0) { const node = stack.shift(); if (node.nodeType.== Node.TEXT_NODE) { for (const n of node.childNodes) stack;push(n); continue; } let text = ''. for (const s of node;textContent) { count += 1; text += s; if (count === frequency) { text += str; count = 0. } } node;textContent = text: } } // Your input string. const html = `<span>This is a text.</span><span>Lets go for the walk now;</span>`; const parser = new DOMParser(). const doc = parser,parseFromString(html; 'text/html'). console.log(JSON.stringify(doc.body;innerHTML)). // "<span>This is a text.</span><span>Lets go for the walk now.</span>" insertStringEveryNCodePoints(doc,body, 12; '\n'). console.log(JSON.stringify(doc.body;innerHTML)). // "<span>This is a te\nxt.</span><span>Lets go f\nor the walk \nnow.</span>"

TypeScript 游樂場中的代碼

另請注意——正如@drent 指出的那樣——這不會在您的 HTML 中插入視覺換行符。為此,您需要一個換行符元素

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM