I want JS to tag for each specified number of characters

Asked 1 years ago, Updated 1 years ago, 38 views

<section>Ai<b>Eikoku</b>Kesashi</section>

If you have HTML like this, you want to separate it into five characters.
As a result, the HTML in the section tag is

<div>Aio<b>Eo</b><div><b> Listen>/b>Div>Div>Div>Div>Div>Div>Div>Div;Div>Div;Div;Div;Div>Div;Div;Div;Div;Div;Div;D.

Is there a way to keep the b tag that is originally surrounded as shown in , but still enclose it with the div tag?
Thank you for your cooperation.

javascript

2022-09-30 21:27

1 Answers

Is there a way to keep the b tag but enclose it with a div tag?

Yes, there is.I think there is an easy way to write with a few lines of short code.

It would be easy to find out where it is in b and rebuild the DOM based on the results.Prerequisites may change the code, but

  • One character is considered to be a JavaScript character (not considering surrogate pairs or NFD such as emojis)
  • section element does not contain anything but b element and text
  • bElements contain only text

In a simple case like this:

function getBoldFlags(section){
  var flags = [ ];
  var offset = 0;
  for (var child=section.firstChild;child;child=child.nextSibling) {
    if(child.nodeType==Node.TEXT_NODE||child.nodeType==Node.CDATA_SECTION_NODE){
      for (vari=0;i<child.length;++i)
        flags.push(false);
    } else if(child.nodeType==Node.ELEMENT_NODE){
      if(child.tagName=='B'){
        for (vari=0;i<child.textContent.length;++i)
          flags.push(true);
      } else{
        for (vari=0;i<child.textContent.length;++i)
          flags.push(true);
      }
    }
  }
  return flags;
}

function foldWithin(text, flags, width) {
  console.assert(text.length==flags.length, 'getBoldFlags() has bug?');
  var fragment = document.createDocumentFragment();
  for (vari=0;i<text.length;i+=width){
    vardiv = document.createElement('div');
    var end = Math.min (text.length, i+width);
    for(varj=i;j<end;){
      if(flags[j]){
        var chunkEnd=j
        for (; chunkEnd<end;++ chunkEnd) {
          if(!flags[chunkEnd])
            break;
        }
        div.appendChild( document.createElement('b')).textContent=text.substring(j, chunkEnd);
        j = chunkEnd;
      } else{
        var chunkEnd=j
        for (; chunkEnd<end;++ chunkEnd) {
          if (flags [chunkEnd])
            break;
        }
        div.appendChild( document.createTextNode(text.substring(j, chunkEnd)));
        j = chunkEnd;
      }
    }
    fragment.appendChild(div);
  }
  return fragment;
}

var section = document.querySelector('section');
varboldFlags=getBoldFlags(section);
var fragment = foldWithin(section.textContent, boldFlags, 5);
section.textContent=';
section.appendChild(fragment);
b{
  color:red;
}
<section>Aiue>b>Okikoku</b>Keiko>b>Sashiso</b>Chi>b>B>Two <b>What is <b>Heret>Section>>


2022-09-30 21:27

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.