Есть только один надежный способ сделать это: пройти через DOM и найти совпадение в каждом текстовом узле.
Эта функция сделает именно это:
function findTextNodeWithMatch(regex, context) {
context = context || document.documentElement;
var childNodes = context.childNodes,
retTextNodes = [],
i = -1, node;
while ( node = childNodes[++i] ) {
if (node.nodeType === 3) {
var m;
while (m = regex.exec(node.data)) {
retTextNodes.push({
node: node,
match: m
});
}
}
if (node.nodeType === 1 && node.nodeName.toLowerCase() !== 'script') {
retTextNodes = retTextNodes.concat( arguments.callee( regex, node ) );
}
}
return retTextNodes;
}
Использование:
var patternToMatch = /\[((?:\\\[|.)*)\]/g;
var matchingNodes = findTextNodeWithMatch( patternToMatch, $('.comment-body p')[0] );
for (var i = 0, len = matchingNodes.length; i < len; i++) {
// Loop through the matching nodes:
// Extract the string you want:
var theMatch = matchingNodes[i].match;
var myString = theMatch[1];
alert( myString );
// Replace the string within the node:
var theNode = matchingNodes[i].node;
theNode.parentNode.replaceChild( document.createTextNode(theNode.data.replace(patternToMatch, '')), theNode );
}
Использование элемента innerHTML
не надежно, так как он может содержать другие элементы, и эти элементы могут иметь атрибуты, которые соответствуют тому, что вы ищете - вы не хотите удалять их по ошибке. ..