views:

2036

answers:

2

First off I don't know much about regex and need to buy a book because it's has proven to me to be difficult to pickup.

Ultimately I want to take a dom element, and replace text within straight brackets "[" and "]" and insert a link around the text, and there may be multiple bracket sets in the string.

function changeTip() {  
        var link = '<a href="' + $('#txtURL').attr('value') + '" target="_blank">';
        $('.tipoftheweektip').html($('#txtTip').attr("value").replace('[', link).replace(']', '</a>'));
    }

This works except:

  • doesnt work on the second set of brackets
  • if there isnt a closing straight bracket, it deletes all the text before the opening straight bracket

I've looked at examples and because straight brackets are used in the regex code, I cant figure out how to look for a bracket and replace it.

Anyone out there that has done something similar that they can share? Thanks in advance.

A: 

Try:

.replace(/\[/g, link).replace(/\]/g, '</a>');

The slashes / denote a regular expression literal. The square brackets [] are escaped with back-slashes . The g at the end of each regex instructs it to act globally.

steamer25
This approach does not ensure matching square brackets. I recommend my solution below.
Doug D
both solutions are great! wish i could do more than one check. Thanks guys!
jonathan hall
+2  A: 
.replace(/\[([^\]]*)\]/g, link + "$1</a>")

which means, find text between [ and ] and replace it with the value of link, the text itself and ''. This ensures matching square brackets. The 'g' means 'do it multiple times (globally)'.

Doug D
This site provides a place to test regular expressions in either JavaScript or .NET. It also contains many samples, but they are not always correct.http://www.regexlib.com/RETester.aspx
Doug D
thanks! You're right, I wasnt thinking about finding matching brackets. I learn something everyday!
jonathan hall