Skip to content

Instantly share code, notes, and snippets.

@matdave
Last active October 23, 2024 20:06
Show Gist options
  • Save matdave/d964dc2ca99001c54a190c65e6c2212d to your computer and use it in GitHub Desktop.
Save matdave/d964dc2ca99001c54a190c65e6c2212d to your computer and use it in GitHub Desktop.
Convert all hyphens to non-breaking
// parse through each element in the document
// replace hyphens with non-breaking hyphens
var elements = document.getElementsByTagName('*');
for (var i = 0; i < elements.length; i++) {
var element = elements[i];
// ignore script and style elements
if (element.tagName === 'SCRIPT' || element.tagName === 'STYLE') {
continue;
}
for (var j = 0; j < element.childNodes.length; j++) {
var node = element.childNodes[j];
// only process text nodes
if (node.nodeType === 3 && node.nodeValue.indexOf('-') !== -1) {
var text = node.nodeValue;
var replacedText = text.replace(/-/g, '‑');
if (replacedText !== text) {
element.replaceChild(document.createTextNode(replacedText), node);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment