gpt4 book ai didi

javascript - 使用 Javascript 中的文本位置(文本跨度)将文本替换为 html 格式

转载 作者:行者123 更新时间:2023-11-28 05:25:12 25 4
gpt4 key购买 nike

我有一个字符串,我想用 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);

关于javascript - 使用 Javascript 中的文本位置(文本跨度)将文本替换为 html 格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33509760/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com