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
You can simply check for ABCD, check how many of it exists in the string, then construct a new string from it like this (you can use space as a separator if it fits your case better):
var res = myStr.match(/ABCD/g);
var str = res ? res.join('') : '';
The ternary is there because match() will return null if it finds nothing - which does not have a join() method.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With