Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex to filter out certain characters

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

like image 410
Marco V Avatar asked Aug 07 '15 19:08

Marco V


People also ask

How do you omit a character in regex?

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.

What does '$' mean in regex?

$ 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.

What is difference [] and () in regex?

[] 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 .


1 Answers

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

like image 200
cнŝdk Avatar answered Sep 30 '22 15:09

cнŝdk