44 lines
1.6 KiB
JavaScript
44 lines
1.6 KiB
JavaScript
// pangu.js - Auto insert spaces between CJK and half-width characters
|
|
(function() {
|
|
// CJK Unified Ideographs + common ranges
|
|
var CJK = '⺀-⼀--ゟ゠-ヿ-ㄯ㈀-㋿㐀-䶿一-鿿豈-︰-﹏-';
|
|
var CJK_RE = new RegExp('([' + CJK + '])', 'g');
|
|
|
|
// Insert space between CJK and half-width (letters, digits, symbols)
|
|
function panguText(text) {
|
|
// CJK followed by half-width
|
|
text = text.replace(new RegExp('([' + CJK + '])([a-zA-Z0-9@#$%&=+<>|\\\\])', 'g'), '$1 $2');
|
|
// Half-width followed by CJK
|
|
text = text.replace(new RegExp('([a-zA-Z0-9@#$%&=+<>|\\\\])([' + CJK + '])', 'g'), '$1 $2');
|
|
return text;
|
|
}
|
|
|
|
function panguNode(root) {
|
|
var walker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT, null, false);
|
|
var nodes = [];
|
|
while (walker.nextNode()) {
|
|
var node = walker.currentNode;
|
|
// Skip code, pre, script, style, input
|
|
if (node.parentElement && node.parentElement.closest('code, pre, script, style, input, textarea')) continue;
|
|
if (node.textContent.length > 1) nodes.push(node);
|
|
}
|
|
nodes.forEach(function(node) {
|
|
var spaced = panguText(node.textContent);
|
|
if (spaced !== node.textContent) node.textContent = spaced;
|
|
});
|
|
}
|
|
|
|
function run() {
|
|
var content = document.querySelector('.post-content');
|
|
if (content) panguNode(content);
|
|
}
|
|
|
|
window.initPangu = run;
|
|
|
|
if (document.readyState === 'loading') {
|
|
document.addEventListener('DOMContentLoaded', run);
|
|
} else {
|
|
run();
|
|
}
|
|
})();
|