wj R.
wj R.

Reputation: 359

How to combine jquery codes with similar functions?

Is it possible to lessen the code or recreate similar code with same function with this: Fiddle here.Thanks

$(".addcolor:contains('red')").html(function(_, html) {
   return  html.replace(/(red)/g, '<span class="red">$1</span>')
});
$(".addcolor:contains('blue')").html(function(_, html) {
   return  html.replace(/(blue)/g, '<span class="blue">$1</span>')
});
$(".addcolor:contains('green')").html(function(_, html) {
   return  html.replace(/(green)/g, '<span class="green">$1</span>')
});

The function of the code is to replace a specific text with span . How about to apply the css directly with the jquery code?

Upvotes: 0

Views: 40

Answers (2)

gaurav5430
gaurav5430

Reputation: 13882

using an array for storing all the color values and creating regex:

var arr = ['red','green','blue'];

for(i=0;i<arr.length;i++){
$(".addcolor").html(function(_, html) {

    var regex = new RegExp("("+arr[i]+")","g");
    htmla = '<span class="'+arr[i]+'">$1</span>';

   return  html.replace(regex, htmla);
});
}

updated fiddle: http://jsfiddle.net/71eyg9gv/10/

Upvotes: 2

austinthedeveloper
austinthedeveloper

Reputation: 2601

While I'm not the best at Javascript regex stuff, here's my Fiddle:

http://jsfiddle.net/71eyg9gv/4/

Basically I made your repeating sections a function and then declared it with the variables.

function addColor(object) {
    $(".addcolor:contains(" + object +")").html(function(_, html) {
        var re = new RegExp(object,"g");
        return  html.replace(re, '<span class="' + object +'">' + object + '</span>')
    });
}

addColor('red');
addColor('blue');
addColor('green');

Upvotes: 0

Related Questions