简体   繁体   中英

Regex replace not working as intended on any browser except chrome

I'm trying to create a function which adds a styled span element around a regex match to create text highlighting within a code element.

I've managed to create a solution, however, it only works as intended on chrome or if the json form it not copied and pasted in. On other browsers such as firefox and edge, it styles text that I did not intend on styling.I have checked my regex using regex101 and everything seems fine.

<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 doesn't. I am not sure what is happening here. I've commented out the other styled spans but they also have the same problem. I've added json for testing below.

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

The regex for targeting the key-names was not working properly. Also, since you're re-using the block variable, it's more efficient to save the selection.

 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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM