StackOverflow 风格的 Javascript 正则表达式图像标签?

标签 javascript regex replace

我正在尝试模仿 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);

http://jsfiddle.net/ASJT6/

最佳答案

你可以这样匹配:

var re = /!\[([^\]]+)\]\[([^\]]+)\]/g;

这是一个example

编辑: second example使用全局修饰符

编辑 2:如果我们将 uuid 视为图像源,您可以像这样替换它:

var text_modifited = text.replace(re, '<img src="$2" alt="$1" />')

jsFiddle example

关于StackOverflow 风格的 Javascript 正则表达式图像标签?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24265374/

相关文章:

regex - 为什么 sed 打印所有行?

Python:用另一个词替换出现的第一个词

Javascript 字符串 regex/.*/gm 不会一次捕获所有行

javascript - 在 JavaScript 中测试未定义

javascript - 捕获 "applied coupon"事件以触发 Woocommerce 中的 JS 函数

javascript - 对象内部表达式 - Javascript

php - 有效模式的 PHP 中的 "preg_match(): Compilation failed: unmatched parentheses"

javascript - 向表中添加新行/列

java - 正则表达式从 Jdbc url 查找主机名

python - 如何使用 Python 中的正则表达式从预定义的子字符串列表中替换或更新 DataFrame 的字符串实例