views:

28

answers:

1

I'd like to use javascript to search a string and automatically insert a closing tag before every occurrence of an opening tag. Here is the test code I've come up with so far:

var str="<span>this <i>is</i> a <i>test</i></span>";
var patt1=/<(?!span)\b\w+>/g;
var patt2=/<\/(?!span)\b\w+>/g;
document.write(str.replace(patt1, '</b>' + str.match(patt1)));

I've successfully got the regular expression in "patt1" to represent any opening tag except for a span. "str.match(patt1)" clearly does not work since it outputs an array of all the values in the string represented by the regular expression. But is there a way to recall each specific item that is being replaced so that I can use a tweaked version of the above code to essentially act as an insertion tool?

Thanks for all your help.

A: 

Use a capturing group in the regular expression, and a backreference in the replacement:

var patt1=/<(?!span)\b(\w+)>/g;
str.replace(patt1, '</$1>$&')

$1 in a replacement string outputs the first capturing group, while $& outputs the entire matched string.

Anon.
Thanks for the help. This worked perfectly once I adjusted it for what I needed. Now I've got the replace statement looking like this. str.replace(patt1, '</b>$
Douglas