javascript - 正则表达式用 img - js 替换字符串
问题描述
嘿,我目前遇到的问题是我想用图像检测文本中的字符串。
{"a":"img1.jpg", "ab":"img2.jpg"}
我目前的正则表达式是:
/(a|ab)/g
当我有这样的文字时:
yeah abc
它用img1.jpg 替换了是的“a”,但它也用“img1.jpg”替换了“ab”c。
我可以通过切换来避免它,/(ab|a)/
但这不是解决方案,因为我有一个巨大的未排序的 json 列表作为表达式(a,ab 只是为了简单起见)。我这样做的原因是用图像替换原生表情符号。
我怎么能说,如果没有 b 跟随,它只替换 a ?
解决方案
按降序对表情符号键进行排序,然后像这样构建您的正则表达式模式:
function replaceEmojis (str) {
const emojis = {
a: { src: 'imgA.jpg', color: 'red' },
abc: { src: 'imgABC.jpg', color: 'green' },
ab: { src: 'imgAB.jpg', color: 'blue' },
bc: { src: 'imgBC.jpg', color: 'orange' }
};
const fnDescendingOrder = ([x, y]) => x > y ? -1 : +(x != y);
const keys = Object.keys(emojis).sort((x, y) =>
fnDescendingOrder(x.length == y.length ? [x, y] : [x.length, y.length])
);
const pattern = new RegExp(keys.join('|'), 'g');
const transformed = str.replace(pattern, m => {
const emoji = emojis[m];
return '<img class="' + emoji.color + '" src="' + emoji.src + '">';
});
return transformed;
};
let str = 'yeah abc ab a abca bcaba';
result.innerHTML = replaceEmojis(str);
img { width: 10px; height: 100%; }
img.red { background: red; }
img.green { background: green; }
img.blue { background: blue; }
img.orange { background: orange; }
<div id="result"></div>
您必须首先按长度降序排序,然后按字母顺序排序。bc
后应检查原因abc
。
推荐阅读
- python - 当我在 Spyder 中运行它以及直接在终端中运行它时,HIGH DPI Tkinter 重新缩放
- c# - 如何反序列化具有结构向量的 json(使用 c++ 发送,使用 c#,wpf 接收)
- java - 在java文件io中序列化
- maxima - Maxima solve 不返回任何解
- c# - C# Visual Studio - 将新下载的项目导入我当前的项目
- vba - IDE 中的 VBA 错误列表
- serialization - 从 protobuf 消息中删除现有字段会导致问题吗?
- tensorflow - 如何将 y_true 的值数组映射到单个值,以便与 Tensorflow 损失函数中的 y_pred 进行比较(Tensorflow/Tensorflow Quantum)
- java - 如何在 OpenAPI 3.0 中定义字节数组
- apache-spark-sql - Spark-sql 数据砖中的变量动态分配值