首页 > 解决方案 > 正则表达式用 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 ?

标签: javascriptregexemoji

解决方案


按降序对表情符号键进行排序,然后像这样构建您的正则表达式模式:

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


推荐阅读