0

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!

1
  • is [card] a token name that should be added as link class so it can essentially be anything? Commented Mar 18, 2011 at 21:05

3 Answers 3

3
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.

Sign up to request clarification or add additional context in comments.

Comments

1
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>");

3 Comments

This will only replace the first instance and will not properly encode the URL. If the card content contains double quotes, it will break
@Mike Samuel: I've changed the globalization of the replacement and encoding has of course been done by U. No need for me to change my answer because it will be identical to yours. But mine will also use token name to append to link class which yours doesn't. ;)
Good catch. I forgot that requirement.
0
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

2 Comments

This will only replace the first instance and will not properly encode the URL. If the card content contains double quotes, it will break.
This will also treat foo[/card][card]bar as the card content of [card]foo[/card][card]bar[/card].

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.