Using Javascript/Jquery Regex with match groups

I'm building custom syntax/markup for an editor I am building. The particular markup would look something like this:

%[--- This is part of the /etc/apache2/sites-available/example.com ---]%

And I want to turn it into

<div class="filerule">This is part of the /etc/apache2/sites-available/example.com</div>

So first I need to match: %[--- This is part of the /etc/apache2/sites-available/example.com ---]% And then I need to match: This is part of the /etc/apache2/sites-available/example.com The regex pattern would look like:

pattern = new RegExp('\\%\\[---(.+?)---\\]\\%','gi');

This entire pattern matches the whole line and the paranthesis define a match "group." When looking for this pattern you will find two matches one for the line ( %[--- This is part of the /etc/apache2/sites-available/example.com ---]%) and one for the text (This is part of the /etc/apache2/sites-available/example.com). You reference these matches by $1, ...,$n where n is the number of that group. The entire line would be $0 where as the text being matched would be $1. Javascript:

$(document).ready(function() {

        function CreateFileRulers(){
        var raw_text = $("#raw_text").text();
        pattern = new RegExp('\\%\\[---(.+?)---\\]\\%','gi');
        raw_text = raw_text.replace(pattern,"
<div class="\"filerule\"">--- $1 ---

        $("#raw_text").html(raw_text);
        }
        CreateFileRulers();

});

html:

<div id="raw_text">
%[--- This is part of the /etc/apache2/sites-available/example.com ---]%
</div>

After document ready the html:

<div id="raw_text">
<div class="filerule"--- This is part of the /etc/apache2/sites-available/example.com ---</div>
</div>
Tagged as jquery
Written by Andrew Konkol on August 9th, 2011

0 Comments

Log in with Twitter, Google, Facebook, LinkedIn to leave a comment.