Get a word broken into syllables and separated by hyphens, without displaying it as

1.7k Views Asked by At

I would like to get a string, of a word broken into one or more syllables, and if more than one, with hyphens, in-between, too.

For example: I would like to get Floccinaucinihilipil-ification out of Floccinaucinihilipilification.

Current browsers are able to break them by hyphens already, grammatical correct.

The reason: I would like to show a term like it would have been shown in a dictionary. Therefor the easiest thing would be to get access to how the browser would break it, but show it in one single line.

In other words: Is there any way to get access to a word as it would be shown to an user agent if there is enough space to show at least the narrowest syllables?

2

There are 2 best solutions below

1
On BEST ANSWER

It's possible, if a bit tedious, to determine where the word wraps are located in the document. But you're also depending on the browser having a hyphenation dictionary, which can depend on the platform and possibly the user's language.

Here's one approach, which works in Firefox. I couldn't get Chrome or WebKit to reliably hyphenate the word at every possible spot, and it simply gave up hyphenating below a certain width.

testbed.innerHTML = testbed.innerHTML.replace(/./g, '<span>$&</span>');
outer = testbed.getBoundingClientRect();
match = [...testbed.querySelectorAll('span:not(:first-child)')].filter(e => e.getBoundingClientRect().x == outer.x);
match.forEach(e => e.classList.toggle('match', true));
output = [...testbed.children].map(e => (e.classList.contains('match') ? '-' : '') + e.textContent).join('');
console.log(output);
div#testbed {
  width: 0;
  hyphens: auto;
}
span.match {
  background: magenta;
}
<div id=testbed lang=en>Floccinaucinihilipilification</div>

0
On

If you want automatic hyphenation you will have to use a third party js library like Hyphenator.

If you want to place marks, such as &shy;, manually, you can do so within the html by hand.