Click here to Skip to main content
14,639,623 members
Rate this:
Please Sign up or sign in to vote.
I am trying to remove all the instances of a number except for a number that I supply. This is currently what I have:

var ar = '10,13,9,8,13,10,5,3,1,9,5,8,10,2,6';
var removed = ar.replace(new RegExp('[^(' + 10 + ')]', 'g'), '')


The result of this is "101110110", but I need it to remove all except those with an exact match. So the result should be ""101010" as there are only 3 "10"'s in the string.

Thanks in advance,

-Dom
Posted
Comments
Garth J Lancaster 15-Aug-13 6:18am
   
I can see how your incorrect answer is obtained - its because you're saying, by putting the '10' in square brackets ie '[10]', that the '1' and '0' are actually a set, of the digits, '1' and '0' - do you agree ? then if you do, I wonder what would happen if you remove the square brackets ... I'd need to play with it and I cant tonight, Im not convinced it can be entirely solved like this - I can see a multiple step process, but Im not sure it helps

1 solution

Rate this:
Please Sign up or sign in to vote.

Solution 1

Try this...
var removed = ar.match(new RegExp('\\b'+10+'\\b','g')).join('');

Regards,
Niral Soni
   
v2
Comments
DominicZA 15-Aug-13 6:41am
   
I gave you 4 stars because this works, 1 more star if you can tell me why :P
Niral Soni 16-Aug-13 9:02am
   
'\b' switch is ANCHORS type regular expression pattern, used to match specified string is a word character and two switches across the string to carry out exact match. RegEx function match() returns the array of all matched strings. So, at the end joining them without any separator to yield required result.

To learn more on JavaScript RegEx, http://tech.pro/tutorial/1214/javascript-regular-expression-enlightenment

Regards,
Niral Soni

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100