2016-10-04 44 views
0

我正在打印一個字符串<a href="..">some text</a>, <a href="..">some other text</a>截斷文本但在javascript中保留html

我想截斷可見文本,但保持鏈接。

如果我只是做了一個天真的子字符串,我會搞砸HTML。

我想確保只顯示100個字符,但如果字符串的最後一部分是,例如,<a hre,那麼這也應該被剝離。

編輯

我已經試過

arr = ['some text', 'some other text', 'some third text']; 
output = arr.map(el => '<a href="#">' + el + '</a>').join(', '); 

// print 
console.log(output.substr(0, 20)) 

但是這會切斷HTML輸出

<a href="#">some tex 

但我想它來計算出的字符數,而不是有多少字符被用來顯示輸出。

因此,如果顯示的輸出是some text, some other text, some third text,我希望它在輸出文本中的字符20而不是html輸出中的字符20中將其剪掉。

+1

推薦顯示到目前爲止你已經嘗試過的東西,因爲它代表你只是要求我們寫你的代碼。 – chazsolo

+0

我已編輯我的問題 – mortensen

+0

在映射數組中的每個值之前,您將必須執行字符計數和截斷。 – chazsolo

回答

0

元素,以任何的設置textContent你想:

(function() { 
 
    var links = document.getElementsByClassName("link"); 
 
    for(var i = 0; i < links.length; i++) { 
 
    links[i].textContent = "Link text changed"; 
 
    } 
 
})();
<a class="link" href="http://stackexchange.com">Stack Exchange</a> 
 
<a class="link" href="http://stackoverflow.com">Stack Overflow</a>

0

你可以用簡單的CSS做到這一點。

var paragraph = document.querySelector('p#before'); 
 

 
    document.querySelector('p#after-text').innerHTML = truncateTEXT(paragraph, 20, true); 
 
    document.querySelector('p#after-html').innerHTML = truncateHTML(paragraph, 20, true); 
 

 
    function truncateHTML(html, limit, dots) { 
 
    holdCounter = false; 
 
    truncatedHTML = ''; 
 
    html = paragraph.innerHTML; 
 

 
    for(index = 0; index < html.length; index++) { 
 
     if(!limit) { 
 
     break; 
 
     } 
 
     if(html[index] == '<') { 
 
     holdCounter = true; 
 
     } 
 
     if(!holdCounter) { 
 
     limit--; 
 
     } 
 
     if(html[index] == '>') { 
 
     holdCounter = false; 
 
     } 
 
     truncatedHTML += html[index]; 
 
    } 
 
    truncatedHTML = correctHTML(truncatedHTML); 
 
    if(dots) { 
 
     truncatedHTML = truncatedHTML + '...'; 
 
    } 
 
    return truncatedHTML; 
 
    } 
 

 

 
    function truncateTEXT(string, limit, dots) { 
 
    string = string.innerText; 
 
    if(string.length > limit) { 
 
     return string.substring(0, limit) + (dots ? '...' : ''); 
 
    } else { 
 
     return string; 
 
    } 
 
    } 
 

 
    function correctHTML(html){ 
 
    container = document.createElement('div'); 
 
    container.innerHTML = html 
 

 
    return container.innerHTML; 
 
    }
<p id="before"><a href="#">Lorem</a> <strong>ipsum</strong> <a href="#">dolor</a> <strong>sit</strong> <a href="#">amet</a> <strong>consectetur</strong> <a href="#">adipiscing</a> <strong>elit</strong></p> 
 
<p id="after-text"></p> 
 
<p id="after-html"></p>

+1

我不認爲OP希望他想截斷案例段中的整個文本而不是鏈接。如果鏈接是最後一個應該被截斷。 – jcubic

+0

嗯,你是對的。我寫了一些簡單的腳本,並希望能夠幫助它。 –