const regex = /^(((1)st?|(2)nd?|(3)rd?|([4-9])th?)|(([0-9]*)(1[0-9])th?)|(([0-9]*[02-9])((1)st?|(2)nd?|(3)rd?|([04-9])th?)))$/igm;
// Alternative syntax using RegExp constructor
// const regex = new RegExp('^(((1)st?|(2)nd?|(3)rd?|([4-9])th?)|(([0-9]*)(1[0-9])th?)|(([0-9]*[02-9])((1)st?|(2)nd?|(3)rd?|([04-9])th?)))$', 'igm')
const str = `// ordinals
1st
22nd
333rd
4444th
2500th
// teens
11th
12th
13th
14th
15th
16th
17th
18th
19th
// teens - hundreds
111th
112th
113th
114th
115th
116th
117th
118th
119th
// teens - wrong suffix
11st
12nd
13rd
111st
112nd
113rd
// uppercase
1ST
22ND
333RD
444TH
// wrong suffix (do nothing)
0th
26st
31th
21rd
29nd`;
const subst = `$3$4$5$6$8$9$11$13$14$15$16`;
// The substituted value will be contained in the result variable
const result = str.replace(regex, subst);
console.log('Substitution result: ', result);
Please keep in mind that these code samples are automatically generated and are not guaranteed to work. If you find any syntax errors, feel free to submit a bug report. For a full regex reference for JavaScript, please visit: https://developer.mozilla.org/en/docs/Web/JavaScript/Guide/Regular_Expressions