簡體   English   中英

JavaScript RegEx - 防止在字符串內部捕獲

[英]JavaScript RegEx - prevent from capturing if inside string

我有以下代碼,一個textarea覆蓋左半邊,一個div覆蓋右半邊。 無論在左側插入什么內容都會被復制到右側,HTML標記( <...> )會以棕色顯示。

我遇到的問題是如何使它成為如果標記在引號或撇號內(將其轉換為字符串),它不會被替換方法中的RegEx模式捕獲(不會變成棕色)。

為了更好地解釋它,將以下文本放在代碼片段的textarea中:

<html>
  <head>
    <script>
      function getString() {
        return "This string's content contains a tag \"<>\" which isn't suppost to be captured by the RegEx pattern in the replace method";
      }
    </script>
  </head>
</html>

 function HtmlEncode(s) { let el = document.createElement("div"); el.innerText = el.textContent = s; s = el.innerHTML; return s; } function textarea_oninput() { let text = document.getElementsByTagName('textarea')[0].value; text = HtmlEncode(text); document.getElementsByTagName('div')[0].innerHTML = text.replace(/&lt;(.*?(?=(?:&gt;)))&gt;/g, "<span style=\\"color: rgb(155, 112, 63)\\">&lt;$1&gt;</span>"); } 
 body { margin: 0px; } textarea { background: rgb(20, 20, 20); border-color: red; color: lightGray; height: 100%; margin: 0px; outline: 0; position: fixed; resize: none; white-space: nowrap; width: calc(50% - 0px); } div { background: rgb(20, 20, 20); border: 1px solid green; color: lightGray; font-family: monospace; height: calc(100% - 4px); left: 50%; margin: 0px; outline: 0; overflow: auto; padding: 2px 0px 0px 2px; position: fixed; resize: none; white-space: pre; width: calc(50% - 4px); } 
 <textarea oninput="textarea_oninput()" spellcheck="false"></textarea> <div></div> 

使得正則表達式模式類似/"|'.+tag.+"|'/是不夠的,因為有\\"\\' '同一個字符串中" "一個字符串內' ,可能更多的是我我想失去考慮。

您必須比HTML標記更早匹配文字字符串:

document.getElementsByTagName('div')[0].innerHTML = text.replace(/"[^"\\]*(?:\\.[^\\"]*)*"|'[^'\\]*(?:\\.[^\\']*)*'|&lt;((?:.(?!&lt;))*)&gt;/g, function(match, p1) {
    return p1 ? "<span style=\"color: rgb(155, 112, 63)\">&lt;" + p1 + "&gt;</span>" : match;
});

注意:很可能是災難性的回溯。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM