Regexp to search/replace only text, not in HTML attribute

后端 未结 6 1305
自闭症患者
自闭症患者 2020-12-11 18:44

I\'m using JavaScript to do some regular expression. Considering I\'m working with well-formed source, and I want to remove any space before[,.] and keep only one space afte

6条回答
  •  南方客
    南方客 (楼主)
    2020-12-11 19:32

    If you can access that text through the DOM, you can do this:

    function fixPunctuation(elem) {
        // check if parameter is a an ELEMENT_NODE
        if (!(elem instanceof Node) || elem.nodeType !== Node.ELEMENT_NODE) return;
        var children = elem.childNodes, node;
        // iterate the child nodes of the element node
        for (var i=0; children[i]; ++i) {
            node = children[i];
            // check the child’s node type
            switch (node.nodeType) {
            case Node.ELEMENT_NODE:
                // call fixPunctuation if it’s also an ELEMENT_NODE
                fixPunctuation(node);
                break;
            case Node.TEXT_NODE:
                // fix punctuation if it’s a TEXT_NODE
                node.nodeValue = node.nodeValue.replace(/ *(,|\.) *([^ 0-9])/g, '$1 $2');
                break;
            }
        }
    }
    

    Now just pass the DOM node to that function like this:

    fixPunctuation(document.body);
    fixPunctuation(document.getElementById("foobar"));
    

提交回复
热议问题