2

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?

NightOwl888
  • 55,572
  • 24
  • 139
  • 212
  • Why do you test per character in your ml_RestrictToChars functions? – Johan Sep 08 '10 at 19:54
  • 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 Sep 08 '10 at 21:52
  • 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 Sep 09 '10 at 06:07
  • 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 Sep 09 '10 at 07:31

1 Answers1

1

Matching every character is simple (but slow), and you show how it works. What you want now is matching a pattern and concatenating all matches. This is done like this:

ml_RestrictToChars = function(input,regex) {
    var rx = new RegExp (regex, 'g');
    var matches = input.match (rx);
    return matches.join ('');
};

The first line makes it a "global" regex, which changes the behavior of match(). The second line returns all matches in an array and the last line joins them into a single string and returns it.

Bas Wijnen
  • 1,288
  • 1
  • 8
  • 17