反轉xpath路徑表達式為html結構(一):單層标簽反轉解析;
var unXpath = function (X){
var A = X.split( / \]\[|\[|\] / ); // 屬性分組處理
A[ 0 ] = A[ 0 ].replace( / (#)(\w+(?=(\s|\.|\[|$))) / , ' id="$2" ' ); // 轉換ID
A[ 0 ] = A[ 0 ].replace( / (\.)(\S+(?=($))) / , ' class="$2" ' ).replace( / \. / g, " " ); // 轉換class
var T = ' <{a}></{b}> ' .replace( / {a} / ,A.join( " " )).replace( / {b} / ,A[ 0 ].split( " " )[ 0 ]); // 組合生成html完整結構
return T.replace( / (\s>|\s{2}\ / > ) / ,">").replace( / ( >< \ / )(input|img|br)(>) / , " /> " ); // 單閉合标簽處理
}
alert(unXpath( ' div#I.me.she.he[id="info"][title="小web"] ' ));
// 傳回<div id="info" class="me she he" title="小web"></div>
alert(unXpath( ' input#Ta.she[type="text"][title="小web"] ' ));
// 傳回<input type="text" id="Ta" class="she" title="小web" />
alert(unXpath( ' input#menu ' ));
// 傳回<input id="menu" />
alert(unXpath( ' br ' ));
// 傳回<br />
alert(unXpath( ' img[src="i.gif"] ' ));
// 傳回<img src="i.gif" alt="" />
轉載于:https://www.cnblogs.com/littleweb/archive/2010/11/28/1890623.html