Trick Jarrett
Trick Jarrett

Reputation: 3577

RegEx Replace with Javascript

I'm struggling with an issue of Javascript RegEx replacement. What I need to do is run a replacement over a paragraph of text looking for "[card]lorem ipsum[/card]"

I found jQuery plugins which allow for regex matching on selectors, such as ids or paragraphs containing text but I didn't find one which would get down to the actual regex text.

So then I went back to the original javascript level of RegEx and kept running into walls.

So can anyone help me?

I need to turn

[card]lorem ipsum[/card] 

into

<a href="http://example.com/lorem+ipsum" class="card">lorem ipsum</a>

Thanks!

Upvotes: 0

Views: 313

Answers (3)

amit_g
amit_g

Reputation: 31250

var s = "[card]lorem ipsum[/card]";
var r = '<a href="http://example.com/$2" class="$1">$2</a>';

var re = /\[(\w+)\](.+?)\[\/\w+\]/ig;

var n = s.replace(re, r); // Would have the result

Upvotes: 0

Robert Koritnik
Robert Koritnik

Reputation: 105009

var rx = /\[card](.+?)\[\/card]/gi;
yourTextVariable.replace(rx, "<a href='http://example.com/$1'>$1</a>");

everything in between will be captured for you.

If card is a variable that should be inserted as class:

var rx = /\[(.+?)](.+?)\[\/.+?]/gi;
yourTextVariable.replace(rx, "<a href='http://example.com/$2' clas='$1'>$2</a>");

Upvotes: 1

Mike Samuel
Mike Samuel

Reputation: 120486

myString.replace(
    /\[card\]([\s\S]*?)\[\/card\]/g,
    function (_, cardContent) {
      return '<a href=\"http://example.com/' + encodeURIComponent(cardContent)
          + '" class="card">' + cardContent + '<\/a>';
    });

should do what you want.

Upvotes: 3

Related Questions