Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Highlighting characters by their number

Consider having the following string and it's numerical value:

enter image description here

You then allow the user to type in to a textbox: 1|17|7|19, how would I be able to highlight the text as follows:

enter image description here

I can have it work when calculating in spaces and paragraphs, but when I completely remove all white space and new lines (e.g. "Thisissomedummytext") I cannot work out how I would go about achieving this.

EDIT

This is what I have so far, it takes into account spaces and new lines (nl's count as 1 char).

like image 717
Prisoner Avatar asked Oct 05 '12 14:10

Prisoner


Video Answer


2 Answers

I'm not sure if this helps, but:

http://jsfiddle.net/mCsuH/1/

It's not the cleanest, and I wasn't sure if you were using jQuery (where it might be easier to do). I'm sure plenty would be changed, such as how/when this event is happening. It's probably not the best to completely rebuild the output for every onkeyup event.

UPDATED:

(to support spaces)

http://jsfiddle.net/mCsuH/2/

NEW UPDATE:

(to support all whitespace)

http://jsfiddle.net/4HFLx/1/

(new logic to actually fix my previous problem provided by @eminor)

like image 68
Ian Avatar answered Oct 11 '22 13:10

Ian


What about have two index, one for iterate the text and another to count the characters?

(I've forked your fiddle @ianpgall)

http://jsfiddle.net/FZHuj/1/

function update() {
    var text = document.getElementById("orig_input").value;
    var mask = document.getElementById("mod_input").value.split("|");

    var char = 0;
    var result = '';
    for (var i = 0; i < text.length; i++) {
        if (/\s/.test(text[i])) {
            result += text[i];
            continue;
        }

        char++;

        if (mask.indexOf(char) === -1)
            result += text[i];
        else
            result += '<span class="mod">' + text[i] + '</span>';
    }

    document.getElementById("output").innerHTML = result;
}

The "char" index counts the valid characters, and we look for this index on the "mask" array.

The "i" index is used to iterate the input text.​

like image 34
A. Matías Quezada Avatar answered Oct 11 '22 13:10

A. Matías Quezada