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

我有一个字符串,我想用HTML字体颜色替换文本,我需要使用包含跨度(键)开始和跨度(值)长度的字典进行替换。 任何想法如何在JS中做到这一点,以便所有的文本被正确替换为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>'.");

总的来说,我想用一些html替换原始字符串,但是使用包含文本开始和子串长度的字典。

非常感谢!


这使用正则表达式来完成工作。 字典按相反顺序处理,以便替换索引不会改变。

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

请参阅JSFiddle上的工作示例。

这是做什么的:

  • 获取文本
  • 设置字典
  • 对于字典中的每个“单词”,请更改原始字符串,使其为:
  • +之前的文字
  • <div style="color: blue">
  • 字典文本
  • </div>
  • 字典文本之后的文本
  • 在旁注中, <font>标签及其color属性已被弃用。 改用CSS。

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

    上一篇: Replace text with html formatting using text location (text span) in Javascript

    下一篇: why wont my font color work