Home > Net >  Word wrap hyphenated text as if it were one word
Word wrap hyphenated text as if it were one word

Time:11-29

I'm trying to wrap hyphenated text on a button as if it were one word. I've tried using a few different variations of the word-wrap and break-word CSS properties but no luck.

In the snippet below, I'm trying to get hello on one line, and this-is-a-test on the next line

const btn = document.getElementById("btn");

btn.innerHTML = 'hello this-is-a-test'
#btn {
  width: 90px;
}
<button id="btn"></button>

CodePudding user response:

In place of your dashes in this-is-a-test you could use non-breaking spaces &nbsp; and you could explicitly put a <br> where the space is. If you have arbitrary text (not a test) you could start with what you have then regex replace &nbsp; wherever there is a - dash, and replace space with <br>

let btnText = 'hello this-is-a-test';
const btn = document.getElementById("btn");

btn.innerHTML = btnText.replaceAll('-','&nbsp;').replaceAll(' ','<br>');
#btn {
  width: 90px;
}
<button id="btn"></button>

CodePudding user response:

You can just replace dashes with &#8209; symbol. Like:

const btn = document.getElementById("btn");

btn.innerHTML = 'hello this-is-a-test'.replace('/-/g', '&#8209;')
  • Related