0

I have a string that will accept the following:

this is the pattern: xxx-A-mmddyyyy-xxxxxx.

The person enters a value either by copying and pasting or hand jams. What I want to do, onBlur(), is make a function that will remove the first dash in either case.

I want the pattern match to be REGEX that only permits the above. The result would be:

xxxA-mmddyyyy-xxxxxx

That's pretty much it.

This is the REGEX patterns for with DASH and how I want it to look 'after' stripping out the first dash:

 public static readonly NUMBERWITHDASH = /^[0-9]{3}-[A-Z]-[0-9]{8}-[0-9]{6}$/;
 public static readonly NUMBERNODASH = /^[0-9]{3}[A-Z]-[0-9]{8}-[0-9]{6}$/;
Destroy666
  • 892
  • 12
  • 19
Peter The Angular Dude
  • 1,112
  • 5
  • 26
  • 53
  • Basically try a replace of `^([0-9]{3})-([A-Z]-[0-9]{8}-[0-9]{6})$` with `\1\2` or `$1$2`, depending on the specific Regex version. – AdrianHHH Apr 11 '23 at 15:42
  • You mean replace the entire Regex with just \1\2 or $1$2 only? That's it?? – Peter The Angular Dude Apr 11 '23 at 15:56
  • You want to remove a hyphen, if present. The two capture groups collect everything except that hyphen. If the regex does not match then the text is not changed. – AdrianHHH Apr 11 '23 at 17:09
  • Does this answer your question? [Reference - What does this regex mean?](https://stackoverflow.com/questions/22937618/reference-what-does-this-regex-mean) – AdrianHHH Apr 11 '23 at 20:49
  • @AdrianHHH I was just asking where to you want me to put your suggestions in the Regex. I know what REGEX means, respectfully. So replace all this: ^([0-9]{3})-([A-Z]-[0-9]{8}-[0-9]{6})$ with \1\2 or $1$2??? That's what I was asking. It's not clear... if you explain where you wanted those replacements, let me know. – Peter The Angular Dude Apr 12 '23 at 13:39
  • Just suggesting to do a regex replacement, the search string would be `^([0-9]{3})-([A-Z]-[0-9]{8}-[0-9]{6})$` and the replacement would be `\1\2` or `$1$2`, depending on the specific Regex version being used. I know regexs, but I do not know Angular, hence I did not write out an answer. I wrote this as a suggestion assuming that you would know how to write the Angular code to do the replacement. If I were doing this in C# then I would do something like `string code = "xxx-A-mmddyyyy-xxxxxx"; code = Regex.Replace(code, "^([0-9]{3})-([A-Z]-[0-9]{8}-[0-9]{6})$", "$1$2");`. – AdrianHHH Apr 12 '23 at 14:14

1 Answers1

1

You don't need a regex for this simple exercise:

let string = 'xxx-A-mmddyyyy-xxxxxx';

const index = 3;

if(string.charAt(index) === '-') {
  string = string.slice(0,index) + string.slice(index+1);
}

console.log(string);

Or even simpler:

let string = 'xxx-A-mmddyyyy-xxxxxx';

const index = 3;

if(string.charAt(index) === '-') {
  string = string.replace('-', '');
}

console.log(string);
Wilt
  • 41,477
  • 12
  • 152
  • 203