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/ ---]%

And I want to turn it into

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

So first I need to match: %[--- This is part of the /etc/apache2/sites-available/ ---]% And then I need to match: This is part of the /etc/apache2/sites-available/ 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/ ---]%) and one for the text (This is part of the /etc/apache2/sites-available/ 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 ---




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

After document ready the html:

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


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