Replace text with html formatting using text location (text span) in Javascript

I have a string and I want to replace text with html font colors and I need to replace using a dictionary containing the start of the span (key) and the length of the span (value). Any idea on how to do this in JS so that all my text is replaced correctly with html?

str = "Make 'this' become blue and also 'that'."

// color_dict contains the START of the span and the LENGTH of the word.
// i.e. this & that are both size 4.

color_dict = {6: "4", 34: "4"};

console.log(str.slice(6, 10));  //obviously this is just a slice
console.log(str.slice(34, 38));

// This is what I would like at the end.

document.write("Make '<font color='blue'>this</font>' become blue and also '<font color='blue'>that</font>'.");

Overall, I'd like to replace the original string with some html but using the dictionary containing the text start and length of the substring.

Thank you so much!


This uses regular expressions to get the job done. The dictionary is processed in reverse order so that the indexes for replacements won't change.

var str = "Make 'this' become blue and also 'that'."

// color_dict contains the START of the span and the LENGTH of the word.
// i.e. this & that are both size 4.
var color_dict = { 6: "4", 34: "4" };

// get keys sorted numerically
var keys = Object.keys(color_dict).sort(function(a, b) {return a - b;});

// process keys in reverse order
for (var i = keys.length - 1; i > -1; i--) {
  var key = keys[i];
  str = str.replace(new RegExp("^(.{" + key + "})(.{" + color_dict[key] + "})"), "$1<font color='blue'>$2</font>");
}

document.write(str);

你可以这样做:

var str = "Make 'this' become blue and also 'that'.";
var new_str = '';
var replacements = [];
var prev = 0;
for (var i in color_dict) {
    replacements.push(str.slice(prev, parseInt(i)-1));
    prev = parseInt(i) + parseInt(color_dict[i]) + 1;
    replacements.push(str.slice(parseInt(i)-1, prev));
}
for (var i = 0; i < replacements.length; i+=2) {
    new_str += replacements[i] + "<font color='blue'>" + replacements[i+1] + "</font>";
}
new_str += str.substr(-1);
console.log(new_str); 
//Make <font color='blue'>'this'</font> become blue and also <font color='blue'>'that'</font>.

HTML :

<div id="string">Make 'this' become blue and also 'that'.</div>

jQuery

var str = $("#string").text(); // get string
color_dict = [{index: 6, length: 4}, {index: 34, length: 4}]; // edited your object to instead be an array of objects

for(var i = 0; i < color_dict.length; i++) {
    str = str.substring(0, color_dict[i].index) +
          "<span style='color: blue'>" + 
          str.substring(color_dict[i].index, color_dict[i].length + color_dict[i].index) + 
          "</span>" + 
          str.substring(color_dict[i].index + color_dict[i].length);
    for(var j = i+1; j < color_dict.length; j++) {
        color_dict[j].index += color_dict[i].length + 29; // shift all further indeces back because you added a string
    }
}

$("#string").html(str); // update string

See the working example on JSFiddle.

What this does is:

  • Get the text
  • Set the dictionary
  • For each "word" in the dictionary, change the original string so that it is:
  • the text before +
  • <div style="color: blue">
  • the dictionary text
  • </div>
  • the text after the dictionary text
  • On a side note, the <font> tag and its color attribute are deprecated. Use CSS instead.

    链接地址: http://www.djcxy.com/p/2512.html

    上一篇: 我怎么知道正确的HTML代码的样子

    下一篇: 用Javascript中的文本位置(文本范围)替换html格式的文本