ic3
ic3

Reputation: 7680

Javascript RegExp to change a line depending on the content

I'm really having trouble with Javascript and regular expression. We've a log file generated with log4J and would like to render into an html page. The idea is to add some styles to the lines depending on the type of error (Warning, info..).

It's possible to create a regular expression that transform each line :

 [                          main] [ WARN] (26-01-12 17:06:09.168) Engine started
 [         startup-schema-loader] [ INFO] (26-01-12 17:06:09.168) Load on Startup Schemas Setup
 [         startup-schema-loader] [DEBUG] (26-01-12 17:06:09.168) dispatching request   [GwtReloadAllSchemasServerRequest : ]
 [               engine-thread-2] [ INFO] (26-01-12 17:06:09.171) Re-loading all schemas

into something like :

<span class="log-warn">[                          main] [ WARN] (26-01-12 17:06:09.168) Engine started</span>
<span class="log-info">[         startup-schema-loader] [ INFO] (26-01-12 17:06:09.168) L</span>

thanks in advance

Upvotes: 0

Views: 63

Answers (1)

Ivan Castellanos
Ivan Castellanos

Reputation: 8243

Here you go, just store the logs inside a var called logs.

var html = logs.replace(/.*/g,function($0){
    var r = $0.match(/[A-Z]+(?=])/g); 
    return r ? '<span class="log-'+ r[0].toLowerCase()+'">' + $0 + '</span>' : $0})

Working example: http://jsfiddle.net/nFwQT/


Explanation: In the first line we "split" every line using regex and apply a function to each one, in the second line we use a regex that match an upper-case word followed by a "]", in the third line we return a SPAN tag with a class based on the matched word or just the element if no match was found.

Upvotes: 3

Related Questions