views:

53

answers:

1

To put this in context, consider these 2 functions:

ml_RestrictToChars = function(input,regex) {
    var result = '';var c = '';
    var rx = new RegExp(regex);
    for (var i = 0; i < input.length; i++) {
        c = input.charAt(i);
        if (rx.test(c)) {
            result += c;
        }
    }
    return result;
};
ml_OmitChars = function(input,regex) {
    var rx = new RegExp(regex,'g');
    return input.replace(rx,''); 
};

The first function will constrain the input to a certain set of characters, the second will omit any character or sequence of characters from the input. As you can see by the code in the first function, it will only function if a single character class is passed into the 'regex' argument because the inclusion code only checks the characters one at a time.

Consider the input string 12-34, right now if I pass a regular expression of '[0-9]' to the first function and '[^0-9]' to the second function, I will get an identical output as expected: 1234

However, if I use a more advanced expression in the second function such as '[^0-9][^0-9]-', I will get an ouput of 12-. But if I pass more than one character class to the first function it will return an empty string.

What I am wondering is if there is an easy way (preferably without looping) to do the inverse of ml_OmitChars so they work similarly?

A: 

Why do you test per character in your ml_RestrictToChars functions?

Johan
@Johan - As a note, this should be a comment as opposed to an answer
joshcomley
If it didnt't test per character using this approach, there would be no way to exclude the characters. That is what the if (rx.test(c)) line does - determine whether each character should be included in the result. I am not saying that this is the only approach to the problem, and I was hoping someone would be able to tackle this from a different perspective.
NightOwl888
Ah, then you could use your omitchars function and return the diff between The original and the omitchars function. That would mirror your functions.
Johan
Ok great, but how could I do that? The only way I can think of is to a) call OmitChars b) loop through each of the characters of the result and c) do a nested loop of the input to remove the characters that are in the result of OmitChars.
NightOwl888