gpt4 book ai didi

javascript - 将每个字符替换为 span

转载 作者:行者123 更新时间:2023-12-01 01:17:33 24 4
gpt4 key购买 nike

我从对象 obj[item].coveredText 获取一些搜索字符串,并希望用跨度替换该搜索字符串的每个字符。

实际上,我只能用一个跨度替换整个搜索字符串。感谢您的提示。

var rangeRoot = $("#plainText");

for (var item in obj) {

var input = rangeRoot.html();
var str = obj[item].coveredText;

var type = obj[item].type;
var level = obj[item].level;
var id = obj[item].id;

var toReplace = str;

var newSpan = '<span data-id="' + id + '" class="annotation level' + level + ' ' + type + '">' + str + '</span>';
var regEx = new RegExp(toReplace, "g");
var output = input.replace(regEx, newSpan);
$(rangeRoot).empty();
$(rangeRoot).append(output);

};

输入示例

这是文本示例

对象

       {
"coveredText": "example",
"type": "exampleType",
"id": 4704,
"level": 2
}

输出

this is an <span data-id="4704" class="annotation level2 exampleType">e</span><span data-id="4704" class="annotation level2 exampleType">x</span><span data-id="4704" class="annotation level2 exampleType">a</span><span data-id="4704" class="annotation level2 exampleType">m</span>

...

最佳答案

要使用正则表达式修复原始代码模式,您应该指定一个替换函数,再次使用 .replace 将每个字符替换为 HTML 文本包围的字符:

const input = `This is an example of an text`;
const obj = {
"coveredText": "example",
"type": "exampleType",
"id": 4704,
"level": 2
};
const { coveredText, type, id, level } = obj;
const pattern = new RegExp(coveredText, 'g');

const replacer = () => (
coveredText.replace(/./g, char => (
`<span data-id="${id}" class="annotation level${level} ${type}">${char}</span>`
))
);
const output = input.replace(pattern, replacer);
console.log(output);

关于javascript - 将每个字符替换为 span,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54603825/

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