Javascript: adding styles to file line by line
I have a plaintext file that is served online using a webserver. It is a log with the following format:
[0开发者_StackOverflow社区0:24:48] <username> message text goes here
I want to make some javascript to format the logs line by line and apply different styles to the timestamp, username and message. How do I read the text in line by line and apply css styles?
Example
var line = "[00:24:48] <username> message text goes here";
// stamp
line = line.replace(/(\[[0-9]{2}:[0-9]{2}:[0-9]{2}\])/, '<span class="stamp">$1</span>');
// username
line = line.replace(/<([a-zA-Z]+)>/, '<span class="user"><$1></span>');
$('#id').html('<div class="message">' + line + '</div>');
I would use jQuery for the ajax just because it's so simple to implement:
$.ajax({
type: 'GET',
url: '/log.txt',
success: function(lines) {
processLines(lines.split('\n'));
}
})
function processLines(arrayOfLines) {
for (var i = 0; i < arrayOfLines.length; i++) {
var line = arrayOfLines[i]; //"[00:24:48] <username> message text goes here";
// stamp
line = line.replace(/(\[[0-9]{2}:[0-9]{2}:[0-9]{2}\])/, '<span class="stamp">$1</span>');
line = line.replace(/<([a-zA-Z]+)>/, '<span class="user"><$1></span>');
$('#id').html('<div class="message">' + line + '</div>');
}
})
You can use a regular expression to generate a single HTML string:
var t = ' [00:24:48] username message text goes here ';
var r = /(\[)([^\]]+)(\] +)(\S+)/g;
var html = t.replace(r, '<span class="timestamp">$2<\/span>' +
'<span class="username">$4<\/span> <span class="message">') +
'<\/span><br>';
// <span class="timestamp">00:24:48</span><span class="username">username</span>'
// <span class="message"> message text goes here </span><br>
though you might need to use the multiline flag (m), depending on the input.
精彩评论