lundi 1 décembre 2014

Highlight multiple substrings in string -- javascript / jquery


tldr: How do I highlight multiple substrings in a javascript string variable (possibly with different colors that are readable with black text)? Simulated Desired Output:


sample_highlight


Long version


I have a span with some text:



<span>This is some text, there are lots of things in here. </span>


I also have a hash containing substrings to highlight:



h = {"t0": [0,2], "t1" : [8,15]}


I would like to highlight the text given the hash of arrays of substring starts and ends. It would look something like this:


This is some text, there are lots of things in here.


I thought about using html tags, but I can't figure out how to replace all the substrings at the same time:


Cumulative Try


First iteration



<tag1>Thi</tag1>s is some text, there are lots of things in here.


Second iteration



<tag1>Th<tag2>i</tag1</tag2>>s is some text, there are lots of things in here.
^ this is where the new 8th index is


Sequential Try


If I do it using the original value, I don't know how to add the results together:


First iteration



<tag1>Thi</tag1>s is some text, there are lots of things in here.


Second iteration



This is <tag2>some tex</tag2>t, there are lots of things in here.


Great! but how do I add those together?





Aucun commentaire:

Enregistrer un commentaire