我想使用Javascript replace()来添加html标记(但它将它们作为字符串返回)

I want to use Javascript replace() to add html tags (but it's returning them as strings)

本文关键字:返回 字符串 标记 添加 Javascript replace html      更新时间:2023-09-26

我有一个简单的javascript函数,它将任意span.certain_class中的"y"字符替换为"I":

$(document).ready(function() {
$('span.certain_class').each(function() {
    $(this).text($(this).text().replace(/y/ig, function(s) {
        return (s === 'Y' ? 'I' : 'i');
    }));
});

});

我遇到的问题是,我想用span:包装替换的字符

<span>i</span>

当我这样做时,浏览器将标记打印为字符串,而不是将它们解析为HTML代码。

有人能帮我解决这个问题吗?

尝试

$(this).html($(this).text().replace........

这将使结果解析为HTML而不是纯文本。

使用$(this).html(...)而不是.text()来设置内容。您可能还想在读取要替换的内容时使用html(取决于它们在您的场景中是什么(。

您应该能够将第一个对text()的调用更改为对html():的调用

$(this).html($(this).text().rep...
$(document).ready(function() {
    $('span.certain_class').each(function() {
        $(this).html($(this).text().replace(/y/ig, function(s) {
            return (s === 'Y' ? 'I' : 'i');
        }));
    });
});

将您的$(this(.text更改为$(this(.html