Owl
Owl

Reputation: 689

Combine filter and regex

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

Answers (2)

Amit Joki
Amit Joki

Reputation: 59232

You can do it this way

$('a').html(function(_,html){
   return html.replace(/\[(.+?)\]/g, "<span class='subtitle'>$1</span>");
});

Upvotes: 1

vks
vks

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

Related Questions