Click here to Skip to main content
15,881,380 members
Please Sign up or sign in to vote.
5.00/5 (1 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:

JavaScript
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

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

Regards,
Niral Soni
 
Share this answer
 
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, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900