簡體   English   中英

正則表達式替換無法在除 chrome 之外的任何瀏覽器上按預期工作

[英]Regex replace not working as intended on any browser except chrome

我正在嘗試創建一個 function ,它在正則表達式匹配周圍添加一個樣式化的 span 元素,以在代碼元素中創建文本突出顯示。

我已經設法創建了一個解決方案,但是,它只能在 chrome 上按預期工作,或者如果 json 形成它沒有復制和粘貼。在其他瀏覽器上,如 firefox 和邊緣,它 ZBC4150D023D3255136DB671D6 不打算在造型上使用的文本我已經使用 regex101 檢查了我的正則表達式,一切似乎都很好。

<pre>
   <code spellcheck="false" id="code" class="json" contenteditable="true">{
    "Id": "12345",
    "Title": "JsonForm",
    "Number": 1,
    "Text": "Text123",
    "Description": []
}</code>
</pre>
<button class="styled-button" onclick="highlight()">style</button>

<script>
  function highlight() {
    let block = document.getElementById('code');
    let formattedText = block.innerHTML;
    var text = formattedText.replace(/(\<span.*?\>|\<\/span\>)/gm, '');

    text = text.replace(/(".*?") *?(?=\:)/gm, "<span style='color: #7fdbca;'>$1</span>")
    //text = text.replace(/("[^\"\<\/\>\\]*?")(?=\,|$)/gm, "<span style='color: #ecc48d;'>$1</span>")
    //text = text.replace(/([0-9]*?)(?=,|$)/gm, "<span style='color: #F78C6C;'>$1</span>")
    block.innerHTML = text;

  }

</script>

https://jsfiddle.net/JacobShore/1xnkejma/22/ On browsers other than chrome, If you click the style button with the preset json it works, however, when you copy and paste the json into the code element and click style it沒有。 我不確定這里發生了什么。 我已經注釋掉了其他樣式的跨度,但它們也有同樣的問題。 我在下面添加了 json 進行測試。

{
    "Id": "12345",
    "Title": "JsonForm",
    "Number": 1,
    "Text": "Text123",
    "Description": []
}

用於定位鍵名的正則表達式無法正常工作。 此外,由於您正在重新使用block變量,因此保存選擇更有效。

 const block = document.getElementById('code'); function highlight() { block.innerHTML = block.innerHTML.replace(/(\<span.*?>|<\/span>)/gm, '').replace(/("[^"]*"):/gm, "<span style='color: #7fdbca;'>$1</span>:"); }
 <pre> <code spellcheck="false" id="code" class="json" contenteditable="true"> { "Id": "12345", "Title": "JsonForm", "Number": 1, "Text": "Text123", "Description": [] } </code> </pre> <button class="styled-button" onclick="highlight()">style</button>

暫無
暫無

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

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