Ole Albers
Ole Albers

Reputation: 9285

Replacing square brackets content to html

I try to change my code highlighting tags to match syntax highlighter from Alex Gorbatchev.

This is how my source code looks like:

[csharp]//awesome code[/csharp]

This is how it should look like:

<pre brush: csharp>//awesome code</pre>

I want to put the allowed tags into an array. So the pseudo code will be something like this:

$.each(allowedValues,function(index,value){
  MagicReplaceFunction(value);
}

So I need something to change my tags before I can call the methods from the code highlighter

jQuery is available.

Upvotes: 1

Views: 623

Answers (1)

Avinash Raj
Avinash Raj

Reputation: 174706

Use string.replace function.

> "[csharp]//awesome code[/csharp]".replace(/\[csharp\]([\s\S]*?)\[\/csharp\]/g, "<pre brush: csharp>$1</pre>")
'<pre brush: csharp>//awesome code</pre>'

[\s\S]*? Matches any space or non-space characters non-greedily. So,

  • \[csharp\] Matches the starting [csharp] tag.
  • ([\s\S]*?) Captures any number of in-between characters.
  • \[\/csharp\] Matches the closing [/csharp] tag.
  • By replacing the matched characters with <pre brush: csharp> plus the characters inside group index 1 plus </pre> will give you the desired output.

Upvotes: 1

Related Questions