Hai Tien
Hai Tien

Reputation: 3117

How to split string and make color for each?

I have a string "I like you" get from h2 element: "<h2 id="demo">I like you</h2>" Now I want split it to make color for each word between two blank spaces. How can I change color for each text in tags. I may use array[i] for each color.

array[1], color:red
array[2], color:green
array[3], color:blue

Color change when onload. Thanks all suggestion.

Upvotes: 1

Views: 791

Answers (3)

Ali
Ali

Reputation: 782

Through simple Javascript,

function str_split (string, split_length) {
   if (split_length === null) {
    split_length = 1;
  }
  if (string === null || split_length < 1) {
    return false;
  }
  string += '';
  var chunks = [],
    pos = 0,
    len = string.length;
  while (pos < len) {
    chunks.push(string.slice(pos, pos += split_length));
  }

  return chunks;
}

Upvotes: 2

Seth McClaine
Seth McClaine

Reputation: 10040

A suggestion until you give a better example of what you're looking for

$(document).ready(function(){
  $.each(array, function(id,value) {
    var color = value.strreplace('color:','');
    $('#'+id).css('color', color);
  });
});

Upvotes: 2

Arun P Johny
Arun P Johny

Reputation: 388416

Try

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

$('#demo').html(function(idx, html){
    return $.map(html.split(/\s/), function(value, idx){
        if(idx < array.length){
            return '<span style="color: ' + array[idx] + '">' + value + '</span>'
        } else {
            return value
        }
    }).join(' ');
})

Demo: Fiddle

Upvotes: 3

Related Questions