Add Space Between English and Chinese

Add spaces between English and Chinese characters, and around A tags in text

当前为 2024-05-18 提交的版本,查看 最新版本

// ==UserScript==
// @name         Add Space Between English and Chinese
// @namespace    http://tampermonkey.net/
// @version      0.1
// @description  Add spaces between English and Chinese characters, and around A tags in text
// @author       mxlg2003
// @match        *://*/*
// @grant        none
// @license      MIT
// ==/UserScript==

(function() {
    'use strict';

    // Function to add space around A tags and between English and Chinese characters
    function addSpaces(node) {
        if (node.nodeType === Node.ELEMENT_NODE) {
            // Process element nodes
            if (node.nodeName !== 'SCRIPT' && node.nodeName !== 'STYLE' && node.nodeName !== 'NOSCRIPT') {
                // Add node around A tags
                if (node.querySelector('a')) {
                    // Replace the content of the node with spaces around A tags
                    node.innerHTML = node.innerHTML.replace(/(<a[^>]*>)(.*?)(<\/a>)/g, ' $1$2$3 ');
                }
                for (let child = node.firstChild; child; child = child.nextSibling) {
                    addSpaces(child);
                }
            }
        } else if (node.nodeType === Node.TEXT_NODE) {
            // Process text nodes
            let text = node.nodeValue;

            // Add spaces between English and Chinese characters
            text = text.replace(/([\u4e00-\u9fa5])([A-Za-z0-9])/g, '$1 $2');
            text = text.replace(/([A-Za-z0-9])([\u4e00-\u9fa5])/g, '$1 $2');
            node.nodeValue = text;
        }
    }

    // Initial run
    addSpaces(document.body);

    // Observe changes in the DOM and apply the function to new nodes
    const observer = new MutationObserver((mutations) => {
        for (const mutation of mutations) {
            for (const node of mutation.addedNodes) {
                addSpaces(node);
            }
        }
    });

    observer.observe(document.body, { childList: true, subtree: true });

})();

QingJ © 2025

镜像随时可能失效,请加Q群300939539或关注我们的公众号极客氢云获取最新地址