Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regular expression to match anything that isn't the string "ABCD"

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
like image 357
brentonstrine Avatar asked Nov 17 '25 20:11

brentonstrine


1 Answers

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('') : '';
  • jsFiddle Demo
  • String.match()
  • Array.join()

The ternary is there because match() will return null if it finds nothing - which does not have a join() method.

like image 160
kapa Avatar answered Nov 20 '25 10:11

kapa



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!