JSFiddle - React, Tailwind, and code Playground
HTML
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>test</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js" type="text/javascript"></script>
</head>
<body>
<div id="original-text">This is some dummy text</div>
<div id="new-text"></div>
</body>
</html>
JavaScript
String.prototype.replaceAt=function(index, char) {
var a = this.split("");
a[index] = char;
return a.join("");
}
$(function(){
// original string of text
var original_string = $("#original-text").text();
// there are no linebreaks in this example, so i'll leave it blank.
var line_breaks = []
// the users string which they provide
// !! NOTE !! in this example I need to include whitespace,
// this is the problem i'm trying to solve
var user_string = "1|12|7|23"
// split each word (if they have more than one word such as "1|2|3 5|1|3"
var words = user_string.split(" ");
// create 1 array with all chars requireing highlighting
var array = [];
for(var i = 0; i < words.length; i++){
array = array.concat(words[i].split("|"));
}
// include line breaks into the array (so we can re-format the block of text)
array = array.concat(line_breaks);
// sort the array largest first (so we can work backwards on the text to not mess with the char indexes
array.sort(function(a,b){return b - a});
// remove duplicate chars
var unique_array = [];
$.each(array, function(i, el){
if($.inArray(el, unique_array) === -1) unique_array.push(el);
});
// loop through the array
for(var i = 0; i < unique_array.length; i++){
var c = unique_array[i];
if($.inArray(c,line_breaks) == -1){
// this item wasn't in our line breaks so lets highlight it!
original_string = original_string.replaceAt(c-1,"<span style=\"color:red; font-weight: bold;\">"+original_string[c-1]+"</span>");
}else{
// this char is a line break, lets break it up!
original_string = original_string.replaceAt(c-1,"<br />");
}
}
// output the new text
$("#new-text").html(original_string);
})