What would a regex string look like if you were provided a random string such as :
"u23ntfb23nnfj3mimowmndnwm8"
and I wanted to filter out certain characters such as 2, b, j, d, g, k and 8?
So in this case, the function would return '2bjd8'
.
There's a lot of literature on the internet but nothing straight to the point. It shouldn't be too hard to create a regex to filter the string right?
ps. this is not homework but I am cool with daft punk
To match any character except a list of excluded characters, put the excluded charaters between [^ and ] . The caret ^ must immediately follow the [ or else it stands for just itself.
$ means "Match the end of the string" (the position after the last character in the string). Both are called anchors and ensure that the entire string is matched instead of just a substring.
[] denotes a character class. () denotes a capturing group. [a-z0-9] -- One character that is in the range of a-z OR 0-9. (a-z0-9) -- Explicit capture of a-z0-9 .
You need to create a regular expression first and then execute it over your string
.
This is what you need :
var str = "u23ntfb23nnfj3mimowmndnwm8";
var re = /[2bjd8]+/g;
alert((str.match(re) || []).join(''));
To get all the matches use String.prototype.match()
with your Regex.
It will give you the following matches in output:
2 b2 j d 8
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