【问题标题】:How to target a letter after a dash in Javascript replace using RegEx?如何在Javascript中使用RegEx替换破折号后定位一个字母?
【发布时间】:2021-01-18 17:46:30
【问题描述】:

我这里有一个脚本,它通过单击按钮来更改文本区域中的值。我使用 Javascript 替换和 RegEx 来做到这一点。所以每个数字都有一个指定的值。

然而,在这个示例中,我无法在破折号后写一个字母来工作。

const mapper = new Map();
mapper.set("10th", "11th");
mapper.set("-", "Deleted");

mapper.set("63-51", "40");
mapper.set("121AA", "95");
mapper.set("121-I", "Deleted");
mapper.set("121-OO", "Deleted");

function fixtext() {
  const elm = document.getElementById("textarea1");
  if (elm) {
    elm.value = elm.value
      .replace(
        /\b\d+(?:[A-Z]|([A-Z])\1|d|th|st|nd)?(|\-\d+)?\b/g,
        m => mapper.has(m) ? mapper.get(m) : m
      );
  }
}
<textarea id="textarea1" rows="4" cols="50">121AA will become 95 and 63-51 will become 40. This should be the same for 121-I and 121-OO.</textarea>

<button class="nbtngreen" onclick="fixtext()">Update</button>

因此,单击按钮后,121-I 应按照指定变为 Deleted121-OO 也是如此。

对于如何修复我正在使用的 RegEx 的任何帮助,我将不胜感激。非常感谢!

【问题讨论】:

  • 还需要匹配-吗?试试/\b\d+(?:-?([A-Z])\1?|[rn]d|th|st)?(?:-\d+)?\b|-/i,见the regex demo
  • \-\d+ 只匹配- 之后的数字,而不是字母。
  • 顺便说一句,你不需要转义 - 除了在 [] 内部。

标签: javascript html regex


【解决方案1】:

您的正则表达式仅匹配- 之后的\d+。将其更改为 [A-Z\d]+ 以匹配那里的字母或数字。

您不需要在带有? 量词的组内使用空字符串的替代选项,因为量词意味着其他模式是可选的。

[A-Z]|([A-Z])\1 可以简化为 ([A-Z])\1?

const mapper = new Map();
mapper.set("10th", "11th");
mapper.set("-", "Deleted");

mapper.set("63-51", "40");
mapper.set("121AA", "95");
mapper.set("121-I", "Deleted");
mapper.set("121-OO", "Deleted");

function fixtext() {
  const elm = document.getElementById("textarea1");
  if (elm) {
    elm.value = elm.value
      .replace(
        /\b\d+(?:([A-Z])\1?|d|th|st|nd)?(-[A-Z\d]+)?\b/g,
        m => mapper.has(m) ? mapper.get(m) : m
      );
  }
}
<textarea id="textarea1" rows="4" cols="50">121AA will become 95 and 63-51 will become 40. This should be the same for 121-I and 121-OO.</textarea>

<button class="nbtngreen" onclick="fixtext()">Update</button>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-08-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-18
    • 1970-01-01
    相关资源
    最近更新 更多