You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在div中高亮特定字符串?jsFiddle中修改日志@符号颜色

Hey there! Let's fix those two issues you're facing with your log viewer page. I'll walk you through adjusting your code to both highlight specific strings in the loaded .txt file and change the color of that @ symbol.

1. Changing the @ Symbol Color in Your Status Text

Your existing status variable has the @ symbol you want to color, but you need to wrap it in a styled HTML element to make the color change stick. Here's how to update that part:

// Your original status text
var status = '<h2><br/><center>I want to change the colour of the >>> @ <<< symbol</center></h2>';
// Replace every @ symbol with a red-colored version (tweak the color value to your preference)
var newStatus = status.replace(/@/g, '<span style="color: #e74c3c; font-weight: bold;">@</span>');
// Inject the styled status into your page (make sure you have an element with id "status" to target)
document.getElementById('status').innerHTML = newStatus;

2. Highlighting Specific Strings in the Loaded Log File

To highlight keywords (like errors, timestamps, etc.) in the log text, we'll modify your openFile function to wrap those target strings in a highlighted span. We'll also switch from innerText to innerHTML so the browser renders the styled HTML:

var openFile = function(event) {
  var input = event.target;
  var reader = new FileReader();
  
  reader.onload = function() {
    var logText = reader.result;
    var outputElement = document.getElementById('output');
    
    // Step 1: Highlight your target string (replace "CRITICAL" with whatever you want to highlight)
    // The `g` regex flag ensures we replace ALL occurrences, not just the first one
    var highlightedLog = logText.replace(/CRITICAL/g, '<span style="background-color: #f1c40f; padding: 0 4px; border-radius: 2px;">CRITICAL</span>');
    
    // Step 2: Optional - Color any @ symbols in the log file too, if needed
    highlightedLog = highlightedLog.replace(/@/g, '<span style="color: #e74c3c;">@</span>');
    
    // Use innerHTML instead of innerText to render the styled content
    outputElement.innerHTML = highlightedLog;
  };
  
  reader.readAsText(input.files[0]);
};

Quick Tips to Customize Further:

  • Adjust Colors: Swap out the hex codes (like #e74c3c for red, #f1c40f for yellow) with any color you want.
  • Highlight Multiple Strings: Add more replace calls to target different keywords, e.g., highlightedLog = highlightedLog.replace(/WARNING/g, '<span style="color: #f39c12;">WARNING</span>');
  • Styling Tweaks: Add CSS properties like font-weight, font-size, or text-decoration to the spans for extra flair.

内容的提问来源于stack exchange,提问作者Mossy Douglas

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 03:44:24