mallendeo
mallendeo

Reputation: 1517

jquery - Select last word of each element if condition

I have a big problem. I have this code http://jsfiddle.net/A7zMa/3/.

I need to add <span> to the last word (in this case the machines model) only if this word has numbers (ex. ZPC85-A10 ---> <span>ZPC85-A10</span>).

I need do this for each h4 element.

The result will be look like this: <h4>some text<span>ZPC85-A10</span></h4> *the hyphen must be included.

Models can be SD34A too, for example.

Sorry for my English, it's not my native language.

Thanks.

Upvotes: 1

Views: 489

Answers (2)

TheHe
TheHe

Reputation: 2972

$('div#main_cont .prod_cont h4.prod_title').each(function(){
    $(this).text($(this).text().replace(/(\w*[\d\-]+\w*)/g, "<span>$1</span>"));
});

Upvotes: 1

Ram
Ram

Reputation: 144659

Try this:

var reg = /([0-9])/g;

$('div#main_cont .prod_cont h4.prod_title').each(function(){
    var s = this.firstChild.textContent.split(" ");
    // or var s = $(this).text().split(" ");
    var last = s[s.length-1];
    if (last.match(reg)) {
       s[s.length-1] = '<span>'+last+'</span>';
    }
    $(this).html(s.join(" "));
})

Fiddle

Upvotes: 1

Related Questions