0

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?

2 Answers 2

2

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/

Sign up to request clarification or add additional context in comments.

3 Comments

yet another good answer. I just really can't say which one is better.
You don't even need the :contains in the selector, you can just remove it.
@DarkAshelin thanks for correcting, i started with the original code , so i missed it.
0

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');

3 Comments

Thanks sir, that one is a lot better I think. Is it possible to include the css on the jquery code? Instead of wrapping it, just directly apply a color.
If they were wrapped in something beforehand, you could directly apply the color. Since they're part of a string, it's not possible to target them with a direct style
Indeed as @austinthedeveloper has said, you can only style elements (with jQuery), not strings.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.