2016-10-04 7 views
0

<a href="..">some text</a>, <a href="..">some other text</a> 문자열을 인쇄 중입니다.텍스트를 자르지 만 자바 스크립트에서 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)) 

을 시도했지만이

<a href="#">some tex 

html로 출력을 차단합니다하지만 얼마나 많은이 대신 표시 문자의 수를 계산하려면 문자가 출력을 표시하는 데 사용되었습니다.

표시된 출력이 some text, some other text, some third text 인 경우 html 출력의 문자 20 대신 문자 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

글쎄, 네 말이 맞아. 간단한 스크립트를 작성하고 도움을 얻을 수 있기를 바랍니다. –