Can someone explain why in order to remove everything but the numbers from a string I have to use the g modifier in javascript? IE:

   function onlyNumbers(input) {
      return input.replace(/[^0-9]/g,'');
   }

but not:

   function onlyNumbers(input) {
      return input.replace(/[^0-9]/,'');
   }

I don't understand the 'g' Global flag and why its necessary. I've never seen / used it in preg_* so I just don't understand what its purpose is or what it really does.

    Derokorian;10995186 wrote:

    Can someone explain why in order to remove everything but the numbers from a string I have to use the g modifier in javascript?

    Without the 'g' flag, Javascript is only going to look for the first replacement and do it. To tell it that you want to globally replace all matches, you need the 'g' flag. Otherwise, .replace() is going to behave the same as [man]preg_replace/man with the 'limit' parameter set to 1.

    Derokorian;10995186 wrote:

    I've never seen / used it in preg so I just don't understand what its purpose is or what it really does.


    Er... did you mean the 'g' flag here again? I'm guessing so, since '/' is the most common delimiter used in regexp's, and all preg
    functions require delimiters.

    EDIT: In case you were referring to the 'g' flag, note that you of course would never see it in PHP code since PHP's [man]preg_replace/man handles that behavior differently, namely through one of the function's parameters.

      I've never seen / used it in preg_* ...

      seen or used... slash represents or in the sentence heh. Yeah I meant the g flag... Thanks for the explanation!

        Write a Reply...