Given a long string in JavaScript, like "Ruby on Rails", and an input string like "ru ra", how could you produce something like <strong>Ru</strong>by on <strong>Ra</strong>ils
, ie Ru by on Ra ils?
My first thought was to tokenize each set of strings and iterate through both sets of tokens, looking for matches, and constructing the new result string as I went. However, I'm not sure how performant this approach is and I often got duplicates. For example, the input "ruby on r" would match for "Ruby" twice, and for "Rails" once.
var original = "Ruby on Rails";
var find = "ru ra";
var posToAdd = [];
var newStr = [];
for (var i = 0; i < original.length; i++) {
newStr.push(original.charAt(i));
}
find = find.split(" ");
for (var i = 0; i < original.length; i++) {
for (var e = 0; e < find.length; e++) {
if (original.substring(i, find[e].length + i).toLowerCase() == find[e].toLowerCase()) {
posToAdd.push(i);
}
}
}
var count = 0;
for (var i = 0; i < posToAdd.length; i++) {
newStr.splice(posToAdd[i] + count, 0, "<strong>");
newStr.splice(posToAdd[i] + count + (find[i].length + 1), 0, "</strong>");
count += 2;
}
var outputStr = "";
for (var i = 0; i < newStr.length; i++) {
outputStr += newStr[i];
}
print(outputStr);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.