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

时间:2015-11-03 21:50:44

标签: javascript html regex string function

我有一个字符串,我想用html字体颜色替换文本,我需要使用包含span(键)的开头和span的长度(值)的字典替换。有关如何在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替换原始字符串,但是使用包含子字符串的文本开头和长度的字典。

非常感谢你!

4 个答案:

答案 0 :(得分:2)

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

&#13;
&#13;
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);
&#13;
&#13;
&#13;

答案 1 :(得分:1)

<强> 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

请参阅working example on JSFiddle

这是做什么的:

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

答案 2 :(得分:1)

你可以这样做:

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>.

答案 3 :(得分:1)

这是一个可以执行此操作的函数,它将字符串和字典作为您定义的格式的参数:

function decorateString(str, color_dict) {
    // turn into more suitable array of {start, len}
    var arr = Object.keys(color_dict).map(function (start) {
        return {
            start: parseInt(start),
            len: parseInt(color_dict[start])
        };
    });
    // sort on descending start position to ensure proper tag-insertion
    arr.sort(function(a, b) {
        return a.start < b.start;
    });
    // build new string and return it
    return arr.reduce(function(str, word) {
        return str.substr(0, word.start) 
            + "<font color='blue'>" 
            + str.substr(word.start, word.len)
            + '</font>' 
            + str.substr(word.start + word.len);
    }, str);
}

按如下方式使用:

str = "Make 'this' become blue and also 'that'."
color_dict = {6: "4", 34: "4"};
document.write(decorateString(str, color_dict));

这是JS Fiddle