[英]Javascript Regexp - Match string pattern except if string is inside specified tag
我試圖替換所有出現的??? some.text.and.dots ??? 在html頁面中添加鏈接。 我已經構建了這個正則表達式:
\\?\\?\\?([A-Z0-9] *)\\?\\?\\?
但是,我想排除鏈接中的任何結果:“<a ...> ...我的模式... </a>”,我對如何做到這一點有點困惑,所有我的嘗試暫時失敗了。
你正在研究什么樣的“HTML”並不是很清楚。 如果它是HTML 代碼 ,可能來自Ajax請求,那么你可以使用正則表達式; 匹配鏈接或模式,然后找出在回調中要做的事情:
var html = document.body.innerHTML;
html = html.replace(/(<a\s.*?>.*?<\/a>)|(\?\?\?([a-z0-9.]*)\?\?\?)/g,
function ( a, b, c, d ) {
return ( a[0] == '<' ) ? a : '<a href="#">' + d + '</a>';
});
context.innerHTML = html;
方便的是, replace()
可以將回調函數作為替換生成器而不是簡單的字符串。
但是,如果您正在處理實時DOM樹,則可能需要尊重節點上的事件而不是簡單地重置innerHTML
。 你需要一個更原始的方法:
// returns all childnodes of type text that do not have A as parent
function walker ( node ) {
var nodes = [];
for (var c, i = 0; c = node.childNodes[i]; i++) {
if ( c.nodeType === 1 && c.tagName !== 'A' ) {
nodes = nodes.concat( arguments.callee( c ) );
}
else if ( c.nodeType === 3 ) {
nodes.push( c );
}
}
return nodes;
}
var textNodes = walker( document.body );
for (var i = 0; i < textNodes.length; i++) {
// create an array of strings separating the pattern
var m = textNodes[i].nodeValue.split( /(\?\?\?([a-z0-9.]*)\?\?\?)/ );
if ( m.length > 1 ) {
for (var j=0; j<m.length; j++) {
var t, parent = textNodes[i].parentNode;
// create a link for any occurence of the pattern
if ( /^\?\?\?([a-z0-9.]*)\?\?\?$/.test( m[j] ) ) {
var a = document.createElement( 'a' );
a.href = "#";
a.innerHTML = RegExp.$1; // m[j] if you don't want to crop the ???'s
parent.insertBefore( a, textNodes[i] );
t = document.createTextNode( ' ' ); // whitespace padding
}
else {
t = document.createTextNode( m[j] );
}
parent.insertBefore( t, textNodes[i] );
}
// remove original text node
parent.removeChild( textNodes[i] );
}
}
此方法僅觸及文本節點,然后僅觸摸與模式匹配的文本節點。
JavaScript本身並不支持后視。 為了做到這一點,你需要運行.match(),然后對於你的每個匹配,你需要在你的標簽上做匹配(比如/<a \\ s +。*你的比賽,然后在你的比賽后</a>。
祝好運!!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.