How do I write a Javascript regular expression that matches everything except a given string (“ABCD”)?
Something like /[^ABCD]/ except I don’t want to match everything that isn’t the letter A, B, C or D. I want to match everything that isn’t the string “ABCD”.
Basically I want this to happen:
var myStr = "ABCA ABCB ABCD BCD ABC"
myStr.replace(/!(ABCD)/g,'') // returns ABCD
Okay, I had misinterpreted the question. It seems you want to test for the presence of
ABCD, and if you find it, replace the whole string with just that:ABCD. This will do that:But it will leave the string unchanged if there’s no
ABCDin it. If you want to delete the string in that case, you have to make the capture optional. But then you have to alter the first part of the regex to make it “sneak up” on the capture:That forces it to try to capture
ABCDat every position. (It also slows things down massively–not an issue in this case, but something to keep in mind if you use this technique on large inputs.)So a pure-regex solution does exist, but I like @bažmegakapa’s solution better. 😀
original answer:
Note that this will also match an empty string. If you have any positive requirements, you can change the
.*to whatever you need. For example, to match one or more uppercase ASCII letters but not the exact stringABCD, you can use: