简体   繁体   中英

How to start a new line with the previous line's word? String/Javascript

I am using D3 to set some text, some of the strings are too long and in the first line I want to cut it with '...' but on the second line how can I start the line with the whole word that was too long on the first line? or perhaps at the end of each last complete word that will fit, leave the '...' then start a new line?

my code:

 d3.selectAll('#titleTable').selectAll('td')
  .data(this.nodes)
  .enter()
  .filter(node => node.parent.id === clickedNode && node.extraExtraNode)
  .append('divname')
  .html(node => {
    const string = node.name.substring(35, 100);
    if (node.name && node.name.length > 35) {
      return ` <div class="nodepic"
       style="
       width: 27px;
       height: 27px;
       border-radius: 100%;
       position: relative;
       top: 17px;
       left: 10px;
       cursor: pointer;
       line-height: 10px;
       float: left;
       background: #eee no-repeat center;
       background-size: cover; background-image: url(https://ewsqa-images.weforum.org/products/${node.id}/standard)"> </div>
      <p class="nodeParagraph">${node.name.substring(0, 35)}..  ${string}</p>`;
    }
    return `<div class="nodepic"
     style=" width: 27px;
     height: 27px;
     border-radius: 100%;
     position: relative;
     top: 17px;
     left: 10px;
     line-height: 10px;
     float: left;
     cursor: pointer;
     background: #eee no-repeat center;
     background-size: cover; background-image: url(https://ewsqa-images.weforum.org/products/${node.id}/standard)"> </div>
     <p class="nodeParagraph">${node.name} </p>`
  })
  .on('click', node => onClick(node))

}

at the moment I am trying to actually add in the rest of the string after the 'dots' by using string after the cut off point..of course this means that the words get cut off and then started again on the next line, at random!

2 possibilities

split your node.name on spaces,

var words = node.name.split(' ');

find the index in the word list that does exceed your 35 length after joining

words.slice(0,i).join(' ').length > 35

or use the following regular expression to split the string larger then 35 chars in two

/(.{1,35}\b)(.*)/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM