skip to Main Content

I am getting below id from api,

F4EF9B435R4T9234FGHDAE34JH5TT4

I need to truncate this text to next line after exact 18 characters like this,

F4EF9B435R4T9234FG
HDAE34JH5TT4

I have tried giving maxWidth but sometimes it is getting truncated after 18 chracters or 17 charachters.

3

Answers


  1. div {
      width: 145px;
      background: #eee;
      word-break: break-all;
      font-family: monospace;
    }
    <div>F4EF9B435R4T9234FGHDAE34JH5TT4</div>
    Login or Signup to reply.
  2. One solution using CSS is as below using max-inline-size :

    #test{
      max-inline-size: 20ch;
      word-break:break-all;
      font-size:15px;
    }
    <div id="test">F4EF9B435R4T9234FGHDAE34JH5TT4</div>

    Adjust the max-inline-size value in ch based on the font-size value.

    If possible, you can achieve the same using javascript also, like in the below code:

    var a = document.getElementById("test").innerText;
    var i = 0;
    var ns = "";
    while (i < a.length) {
      ns += a.substr(i, i + 18) + "n";
      i = i + 18;
    }
    document.getElementById("test").innerText = ns;
    <div id="test">F4EF9B435R4T9234FGHDAE34JH5TT4</div>
    Login or Signup to reply.
  3. Use ch unit to truncate string after specific character length.

    div {
                width: 18ch;
                background: #eee;
                word-break: break-all;
                font-family: monospace;
            }
    <div>F4EF9B435R4T9234FGHDAE34JH5TT4</div>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search