Consider having the following string and it's numerical value:
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:
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).
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)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With