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
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"));