Grambam
Grambam

Reputation: 554

Word wrap hyphenated text as if it were one word

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>

Upvotes: 1

Views: 67

Answers (2)

Andrew Firebug
Andrew Firebug

Reputation: 11

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

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

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

Upvotes: 1

Stephen P
Stephen P

Reputation: 14800

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>

Upvotes: 1

Related Questions