1

What I have here is a script that changes the value in a textarea via onclick of a button. I do this using Javascript replace together with RegEx. So there's a specified value for every number.

In this sample, however, I couldn't make a letter after a dash to work.

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>

So after a click of the button, 121-I should become Deleted as specified. That's also the case for 121-OO.

I'd appreciate any help on how to fix the RegEx I'm using. Many thanks in advance!

3
  • 1
    Do you also need to match -? Try /\b\d+(?:-?([A-Z])\1?|[rn]d|th|st)?(?:-\d+)?\b|-/i, see the regex demo. Commented Jan 18, 2021 at 17:51
  • 1
    \-\d+ only matches numbers after -, not letters. Commented Jan 18, 2021 at 17:55
  • 1
    BTW, you don't need to escape - except inside []. Commented Jan 18, 2021 at 17:56

1 Answer 1

2

Your regexp only matches \d+ after -. Change that to [A-Z\d]+ to match letters or digits there.

You don't need an alternative with an empty string inside a group with a ? quantifier, since the quantifier means the other pattern is optional.

[A-Z]|([A-Z])\1 can be simplified to just ([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>

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.