0

I work with JavaScript on my bachelor thesis.

I would like to read a string and mark the elements that are the same and follow each other in the same color.

I have not found a good approach yet.

I would be grateful for a good proposal.

This is what i have right now.

      function colorsetting(input){
        var collength = input.length;
        var now = '', last2 = '', colored = '';
        now = last2 = input[0];

        for(var i = 1; i <= collength, i++){
          if(now !== last2){
            colored = last2.fontcolor("green");
            last2 = now;
          }
          now = input[i];
        }
        colored = last2.fontcolor("red");

          return colored;
      }
TheMB
  • 5
  • 5
  • 6
    Can you provide some examples of what your input and expected output would be? – Cerbrus Aug 13 '19 at 07:40
  • I work with the rle algorithm. input like: aaaasssssdddddd output like:5a4s5d But i what to show how rle works. so the input string should first be shown in color – TheMB Aug 13 '19 at 07:43
  • Are you looking for certain patterns in your thesis? Or are you trying to go through all of the text and color anything that matches an input? – user11809641 Aug 13 '19 at 07:44

1 Answers1

2

You can split up your input string using a regex:

/(.)\1*/g

(.) grabs any character, and stores that in capture group 1.
\1* then tells the regex to match as many of those as it can.

Then, iterate over that array, wrap the strings in a span, each with their own colour.

const str = "aaaabbbb123aaaaccccz";
const result = str.match(/(.)\1*/g);

console.log(result);

result.forEach(t => {
  // Create a span element
  const span = document.createElement("span");
  
  // Set the text in that span to be the current match
  span.innerText = t;

  // Set the span's color to something random.
  span.style.color = "#"+((1<<24)*Math.random()|0).toString(16);
  
  document.body.append(span);
})

(random color code from here)

Cerbrus
  • 70,800
  • 18
  • 132
  • 147