We have a hyphenated word that we use frequently on our website and we never want it to wrap or break - we always want the two parts of the word on the same line.
Is there a way to make every instance of this word on the site non-breaking or do I have to do it with something like "white-space: nowrap"
in a span around every instance of the word?
Ideally, would love to be able to do an update where every instance of the word that exists on the site becomes non-breaking, without having to manually go and update each word.
Thanks!
Similar to the non-breaking space
, look into the non-breaking hyphen ‑
:
Hello‑World
This will render as Hello‑World
, however it won't be broken up in two lines.
The fastest way to replace some text globally on a website is to walk through only text nodes inside a DOM tree.
You can achieve that by using document.createTreeWalker
and then replacing only text nodes containing the word (or character) you want to change.
var findAndReplaceText = function(el, from, to) {
if (!el || !from || !to) {
return;
}
var node, nodes = [];
var walker = document.createTreeWalker(el, NodeFilter.SHOW_TEXT);
// Find nodes
while (node = walker.nextNode()) {
if (from instanceof RegExp) {
from.test(node.wholeText) && nodes.push(node);
} else {
node.wholeText.indexOf(from) !== -1 && nodes.push(node);
}
}
// Change DOM
while (nodes.length > 0) {
//nodes[0].replaceWith(
// document.createTextNode(nodes[0].wholeText.replace(from, to))
//);
nodes[0].textContent = nodes[0].wholeText.replace(from, to)
nodes.splice(0, 1);
}
};
findAndReplaceText(document.getElementById('fake-hyphens'), /[\u002d\u2010]/g, '\u2011');
findAndReplaceText(document.documentElement, 'lol', 'non');
// \u2010 - hypen
// \u2011 - non-breakable hyphen
// \u002d - minus
section {
float: left;
line-height: 1em;
margin-left: 1em;
}
section p {
width: 200px;
outline: dashed red 1px;
padding: 1em;
}
<section id="fake-hyphens">
<header>Replace to lol-breakable hyphens</header>
<p>one-half mother-in-law eighty-six one-third merry-go-round well-being mass-produced over-the-counter daughter-in-law merry-go-round</p>
</section>
<section>
<header>Without replacement for comparison</header>
<p>one-half mother-in-law eighty-six one-third merry-go-round well-being mass-produced over-the-counter daughter-in-law merry-go-round</p>
</section>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With