我正在尝试模仿 Stackoverflow 处理图像的方式。因此,如果文本中有图像,我会放入一个由图像描述和图像的 uuid 组成的标签:
![image description][3f5e7278-425d-4e75-9beb-59b6770b46a7]
使用 Javascript,我现在想要获取一段文本,获取此标签的所有出现位置,获取图像描述和 uuid,并将该标签替换为适当的 <img
标签,以便我可以将它们加载到我的 Backbone View 中。不过,我对正则表达式有点菜鸟。所以我从这个开始:
var text = 'First some normal text ![image description][3f5e7278-425d-4e75-9beb-59b6770b46a7] and some more text here. And yet another image tag here: ![other img descript.][41f4fd84-0489-4d7a-8923-24d472008655]';
var re = new RegExp('[!\[.*\]\[.+\]]');
var m = re.exec(text);
if (m == null) {
alert(text);
} else {
alert('found some occurrences, but what to do with it?');
}
所以我第一次尝试了正则表达式,这似乎不正确。其次,我真的不知道如何使用它来获取图像描述和uuid。
有人可以帮我解决正则表达式以及如何从中获取图像描述和 uuid 吗?欢迎所有提示!
[编辑] 感谢@Teneff 的回答,我现在做了如下所示的内容。不幸的是,这不起作用,因为它总是警告空。知道我在这里做错了什么吗?
function imgTagToHtmlTag(text) {
var re = /!\[([^\]]+)\]\[([^\]]+)\]/g;
var m;
while ((m = re.exec(text)) != null) {
if (m.index === re.lastIndex) {
re.lastIndex++;
}
}
alert(m);
// View your result using the m-variable.
// eg m[0] etc.
}
var text = 'First some normal text ![image description][3f5e7278-425d-4e75-9beb-59b6770b46a7] and some more text here. And yet another image tag here: ![other img descript.][41f4fd84-0489-4d7a-8923-24d472008655]';
imgTagToHtmlTag(text);
最佳答案
你可以这样匹配:
var re = /!\[([^\]]+)\]\[([^\]]+)\]/g;
这是一个example
编辑: second example使用全局修饰符
编辑 2:如果我们将 uuid 视为图像源,您可以像这样替换它:
var text_modifited = text.replace(re, '<img src="$2" alt="$1" />')
关于StackOverflow 风格的 Javascript 正则表达式图像标签?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24265374/