다중
태그로 html을 JavaScript의 적절한 주변

태그로 변환하는 쉬운 방법이 있습니까?

StackOverflow https://stackoverflow.com/questions/1275250

문제

아래와 같은 HTML이 많이 있다고 가정 해 봅시다.

bla bla bla long paragraph here
<br/>
<br/>
bla bla bla more paragraph text
<br/>
<br/>

JavaScript가 적절한 의미로 변환 할 수있는 쉬운 방법이 있습니까? <p> 태그? 예 :

<p>
  bla bla bla long paragraph here
</p>
<p>
  bla bla bla more paragraph text
</p>

출력 간격은 중요하지 않습니다. 이상적으로는 모든 입력 간격과 함께 작동합니다.

나는 성폭력을 요리하려고 할 것이라고 생각하지만, 내가하기 전에 나는 a) 상처의 세상을 피하고 b) 다른 것이 없었습니다. Google 검색이지만 아직 아무것도 생각하지 못했습니다.

조언에 감사드립니다!

도움이 되었습니까?

해결책

나는 지루해졌다. 최적화 / 조정이 필요하다고 확신합니다. 약간의 jQuery를 사용하여 마법을합니다. FF3에서 일했습니다. 그리고 당신의 질문에 대한 대답은 매우 "간단한"방법이 없다는 것입니다 :)

$(function() {
  $.fn.pmaker = function() {
    var brs = 0;
    var nodes = [];

    function makeP()
    {
      // only bother doing this if we have nodes to stick into a P
      if (nodes.length) {
        var p = $("<p/>");
        p.insertBefore(nodes[0]);  // insert a new P before the content
        p.append(nodes); // add the children        
        nodes = [];
      }
      brs=0;
    }

    this.contents().each(function() {    
      if (this.nodeType == 3) // text node 
      {
        // if the text has non whitespace - reset the BR counter
        if (/\S+/.test(this.data)) {
          nodes.push(this);
          brs = 0;
        }
      } else if (this.nodeType == 1) {
        if (/br/i.test(this.tagName)) {
          if (++brs == 2) {
            $(this).remove(); // remove this BR from the dom
            $(nodes.pop()).remove(); // delete the previous BR from the array and the DOM
            makeP();
          } else {
            nodes.push(this);
          }
        } else if (/^(?:p)$/i.test(this.tagName)) {
          // these tags for the P break but dont scan within
          makeP();
        } else if (/^(?:div)$/i.test(this.tagName)) {
          // force a P break and scan within
          makeP();
          $(this).pmaker();
        } else {
          brs = 0; // some other tag - reset brs.
          nodes.push(this); // add the node 
          // specific nodes to not peek inside of - inline tags
          if (!(/^(?:b|i|strong|em|span|u)$/i.test(this.tagName))) {
            $(this).pmaker(); // peek inside for P needs            
          }
        } 
      } 
    });
    while ((brs--)>0) { // remove any extra BR's at the end
      $(nodes.pop()).remove();
    }
    makeP();
    return this;
  };

  // run it against something:
  $(function(){ 
    $("#worker").pmaker();
  });

그리고 이것은 내가 테스트 한 HTML 부분이었습니다.

<div id="worker">
bla bla bla long <b>paragraph</b> here
<br/>
<br/>
bla bla bla more paragraph text
<br/>
<br/>
this text should end up in a P
<div class='test'>
  and so should this
  <br/>
  <br/>
  and this<br/>without breaking at the single BR
</div>
and then we have the a "buggy" clause
<p>
  fear the real P!
</p>
and a trailing br<br/>
</div>

그리고 결과 :

<div id="worker"><p>
bla bla bla long <b>paragraph</b> here
</p>
<p>
bla bla bla more paragraph text
</p>
<p>
this text should end up in a P
</p><div class="test"><p>
  and so should this
  </p>
  <p>
  and this<br/>without breaking at the single BR
</p></div><p>
and then we have the a "buggy" clause
</p><p>
  fear the real P!
</p><p>
and a trailing br</p>
</div>

다른 팁

동봉 요소의 각 자식 요소 + 텍스트를 스캔하십시오. "BR"요소가 발생할 때마다 "P"요소를 만들고 보류중인 모든 물건을 추가하십시오. 거품, 린스, 반복.

새로운 "P"요소로 이전하는 물건을 제거하는 것을 잊지 마십시오.

나는 찾았다 이 라이브러리 (Propolypothe.js) 이런 종류의 일에 유용합니다.

나는 당신이 실제로 다른 것을 허용하지 않는다고 가정하고 있습니다. <br /> 요소가 나쁘다), 당신은 이중 인스턴스 만 돌리고 싶다. <br /> 단락으로 깨집니다.

그렇게함으로써 나는 :

  1. 모든 라인 브레이크를 제거하십시오
  2. 단락에 전체를 감싸십시오
  3. 바꾸다 <br /><br /> ~와 함께 </p>\n<p>
  4. 마지막으로 빈을 제거하십시오 <p></p> 생성되었을 수있는 요소

따라서 코드는 다음과 같습니다.

var ConvertToParagraphs = function(text) {
    var lineBreaksRemoved = text.replace(/\n/g, "");
    var wrappedInParagraphs = "<p>" + lineBreaksRemoved + "</p>";
    var brsRemoved = wrappedInParagraphs.replace(/<br[^>]*>[\s]*<br[^>]*>/gi, "</p>\n<p>");
    var emptyParagraphsRemoved = brsRemoved.replace(/<p><\/p>/g, "");
    return emptyParagraphsRemoved;
}

메모: 나는 그 과정을 보여주는 것을 매우 장악했다. 물론 당신은 그것을 단순화 할 것입니다.

이것은 샘플을 바꿉니다.

bla bla bla long paragraph here
<br/>
<br/>
bla bla bla more paragraph text
<br/>
<br/>

안으로:

<p>bla bla bla long paragraph here</p>
<p>bla bla bla more paragraph text</p>

그러나 그것은 제거하지 않고 그렇게합니다 <br /> 실제로 원하는 요소.

여러 단계로 할 것입니다.

  1. regexp : 모든 BR- 태그를 라인 브레이크로 변환합니다.
  2. Regexp : 모든 흰색 공간을 벗겨냅니다.
  3. Regexp : 여러 줄 브레이크를 단일 라인 브레이크로 변환합니다.
  4. 결과에 Array.split ( ' n')를 사용하십시오.

그것은 모든 '실제'단락이있는 배열 (이론적으로)을 제공해야합니다. 그러면 그것을 통해 반복하고 각 줄을 p- 태그로 감을 수 있습니다.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top