I am trying to match a string containing a mix of digits and hyphenated digits, like a crossword answer specification, for example 1,2-2 or 1-1,3,4,2-2
/,?(([1-9]-[1-9])|([1-9]))/g is what I’ve come up to match the string
value = value.replace(/,?(([1-9]-[1-9])|([1-9]))/g, '');
replaces ok, and I’ve checked it out in an online tester.
What I really need is to negate this, so I can use it on a keyup event, examine the contents of a textarea and remove characters that don’t fit, so it only allows through characters as in the example.
I’ve tried ^ where expected, but this it’s not doing what I expect, how should I negate the regex so I remove everything that doesn’t match?
If there is a better way of doing this I’m open to suggestions too.
You can use String#match. With
/gflag, it returns an array of all the matches, then you can use Array#join to join them.The problem is that String#match returns null when there is no match, so you have to handle that case and use an empty array so that it can join:
Note: It may better to check them on
onblurrather thanonkeyup. Messing with the text that the user is currently typing will make it annoying. Better to wait for the user to finish typing.