ngplayground
ngplayground

Reputation: 21657

jQuery shortening this query down?

Is it possible to shorten this query's down into one at all?

$('p:contains(Tel:)').html(function() {
    return $(this).html().replace('Tel:', '<strong>Tel:</strong>');
});
$('p:contains(Fax:)').html(function() {
    return $(this).html().replace('Fax:', '<strong>Fax:</strong>');
});

My code looks for Tel: and Fax: and wraps them with the <strong> tag

Upvotes: 1

Views: 70

Answers (1)

Denys S&#233;guret
Denys S&#233;guret

Reputation: 382354

You can merge them as :

$('p:contains(Tel:), p:contains(Fax:)').html(function(_, html) {
    return html.replace(/(Tel\:|Fax\:)/g, '<strong>$1</strong>');
});

But in fact this is a little redundant : you ask jQuery to make a first search before you do your own.

I would personally prefer this :

$('p').each(function() {
    var html = $(this).html();
    var changed = html.replace(/(Tel\:|Fax\:)/g, '<strong>$1</strong>');
    if (changed!=html) $(this).html(changed);
});

Demonstration (click "Run with JS")

Upvotes: 5

Related Questions