如何将属性添加到自定义HTML键[img] /path/to/image.jpg [/ img]?

问题描述 投票:0回答:1

我有一个在线文本编辑器,非常好,但它目前不支持图像。

我现在有这个,并不觉得这是一个很好的方式。

var = txt = "some text here oh and here's my image! [img]linktoimage.jpg[/img]";
var = txt.replace(/[img]/g, '<img src="');
var = txt.replace(/[/img]/g, '" alt="" />');
return txt;

我将如何添加属性?

javascript image replace src
1个回答
2
投票

我会使用替换函数,将子字符串替换为整体并更容易构建替换字符串:

txt = txt.replace(/\[img\](.*?)\[\/img\]/g, function(match, src) {
    return '<img src="' + src + '" alt="" />';
});

有关更多信息,请查看MDN documentation

© www.soinside.com 2019 - 2024. All rights reserved.