[英]Regex to match pattern or match everything else - match precendence issue?
[英]Regex to match everything outside of a regex pattern
因此,我想使用javascript替換正文中HTML標記之外的所有單詞。 檢查以下說明。
我想將其轉換為:
<tag with-attr="something"></tag><tag>Text to match</tag><tag>Text to Match</tag>
...對此:
<tag with-attr="something"></tag><tag>Manipulated Text</tag><tag>Manipulated Text</tag>
現在,我有一個可以匹配所有標記及其包含文本的正則表達式:
\<[^>]*\>
但是,我不確定如何invert
表達式。
編輯
另外,我希望使用replace
/ match
功能,而不是split
,因為我想保留標簽信息並向工作頁面吐出新信息。
使用包含paren的splitExp)RegExp和其他數組方法可以使“流處理”變得相當簡單:
'<tag with-attr="something"></tag><tag>Text to match</tag>Text to Match<tag>'
.split(/(<[^>]+>)/).map(function(x,i){
if(!(i%2) && x){ x= escape(x); }
return x;
}).join("");
示例輸出:
"<tag with-attr="something"></tag><tag>Text%20to%20match</tag>Text%20to%20Match<tag>"
escape()只是為了表明textContent確實已被更改...我只保證在您的示例附近提供輸入。 深度嵌套或無效的HTML可能會欺騙任何RegExp,但是我敢肯定會有其他人提出來...
像這樣
/>([^<>]*\w)</
演示在這里: http : //rubular.com/r/2QPLjOeMAu
現在,您只需要替換以下內容:
var str = '<tag with-attr="something"></tag><tag>Text to match</tag><tag>Text to Match</tag>';
var res = str.replace(/>([^<>]*\w)</g, '>Manipulated text<');
console.log(res);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.