Involve part of a string

2

I'm testing a function to select the part of a title that comes after the colon:

$('.carousel .item .carousel-caption h2').each(function(){
        var val = $(this).text();
        console.log(val);
        var string = val.substr(val.indexOf(":") + 1);
        console.log(string);

        var foo = val.replace('/('+string+')/g', '<span>$1</span>');
        console.log(foo);
    });

I can select the part I need, but I can not include the tags. In the console, the variable foo appears equal to variable val.

    
asked by anonymous 05.08.2014 / 21:03

3 answers

4

You can not concatenate a string in a literal regular expression as you are trying (in fact, you ended up using a string instead of the literal regex). Use the RegExp constructor:

var foo = val.replace(new RegExp('('+ string + ')', 'g'), "<span>$1</span>");

Then, do not forget to replace the value of the element (I assume the intention is this):

$(this).html(foo);
    
05.08.2014 / 21:16
0

Resolved:

   $('.carousel .item .carousel-caption h2').each(function(){
        var val = $(this).text();
        var string = val.substr(val.indexOf(":") + 1);
        var re = new RegExp(string, "g");
        var novo = val.replace(re, '<span>'+string+'</span>');
        $(this).html(novo);
    });
    
05.08.2014 / 21:18
0

Or the uncomplicated way:

$('.carousel .item .carousel-caption h2').each(function(){
        $(this).html( $(this).html().replace(':', ':<span>') + '</span>' );
    });

Or with verification of ':' :

$('.carousel .item .carousel-caption h2').each(function(){
        $(this).html( $(this).html().replace(':', ':<span>') + ($(this).html().indexOf(':') > 0 ? '</span>' : '') );
    });
    
06.08.2014 / 21:13