Wrapping part of a string

Asked

Viewed 71 times

2

I’m testing a function to select the part of a title that comes after the two-point sign:

$('.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’t include the tags. In the console, the foo variable appears equal to the val variable.

3 answers

4


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

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

Then, don’t forget to replace the value of the element (I suppose the intention is this):

$(this).html(foo);

0

Or the uncomplicated way:

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

Or with verification of the existence of ':':

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

0

Solved:

   $('.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);
    });
  • Marcelo, I’m glad you were able to solve and put the final code here. However it would be correct to mark as accepted the answer that led him to solve the problem.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.