Javascript unique strings with RegExps
Wednesday, 4 February 2009
I wrote a cool new feature for Hackvertor which found unique strings in some text, basically the function took a argument of a regular expression to split the text into parts and then scan a dynamic reg exp to check if the strings were unique are not.
I thought I’d run through the code as a change from my usual posts which are usually about hacking javascript.
function unique(regexp, code) {
code = code.split(regexp);
var result = [];
var found = "";
for(var i=0;i
I used RegExp.test because it returns true or false and is much faster than match. The found string builds a dynamic RegExp of all the strings matched and checks their boundaries if they end or start with numbers or text. This is to stop parts of strings being matched and allowing strings within quotes etc. I also escape any RegExp characters matched in the text and return a string of the matches separated by commas.
Here is the Hackvertor tag in action:-
Hackvertor unique tag