Reputation: 689
I want to replace the content of a tag in brackets with a span
Example Text
<a href="#">Linkname [subtitle]</a>
Result should be
<a href="#">Linkname <span class="subtitle">subtitle</span></a>
What I have tried so far:
jQuery(document).ready(function() {
jQuery( "a" )
.contents()
.filter(function(){
return this.match(\[.*\]);
})
.wrap( "<span class='subtitle'></span>" );
});
But I am getting the error "Uncaught SyntaxError: Unexpected token ILLEGAL"
Upvotes: 0
Views: 68
Reputation: 59232
You can do it this way
$('a').html(function(_,html){
return html.replace(/\[(.+?)\]/g, "<span class='subtitle'>$1</span>");
});
Upvotes: 1
Reputation: 67968
var re = /\[([^\]]*)\]/g;
var str = '<a href="#">Linkname [subtitle]</a>';
var subst = '<span class=\'$1\'>$1</span>"';
var result = str.replace(re, subst);
See demo.
http://regex101.com/r/rA7aS3/4
Upvotes: 0