RegExp for hyphen to camelCase?

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • RobG

    RegExp for hyphen to camelCase?


    I'm messing with getPropertyValu e (Mozilla et al) and currentStyle (IE)
    and have a general function (slightly modified from one originally
    posted by Steve van Dongen) for getting style properties:

    function GetCurrentStyle ( el, prop ) {
    if ( window.getCompu tedStyle ) {
    // Mozilla et al
    return window.getCompu tedStyle(el, '').getProperty Value(prop) );
    } // IE5+
    else if ( el.currentStyle ) {
    return el.currentStyle[prop];
    } // IE4
    else if ( el.style ) {
    return el.style[prop];
    }
    }

    If property names have no hyphen (e.g. width, height) then all is fine.
    But with hyphenated names (e.g. margin-right, border-top) Mozilla
    wants them unmodified and IE wants them camelCased (marginRight, borderTop).

    Is there a simple RegExp that will camelCase hyphenated strings? I can
    do it with a loop and string operations but would prefer to use a single
    RegExp if possible.

    The following works fine using substring (for s having 0 or more
    hyphens) but is there a simpler way?

    function toCamel ( s ) {
    s = s.split('-');
    var i=0, j=s.length;
    while ( ++i < j ) {
    s[0] += s[i].substring(0,1) .toUpperCase() + s[i].substring(1);
    }
    return s[0];
    }

    I've tried using RegExp but can't get a simple expression without
    looping - property names have up to 3 (or more? three-d-light-shadow)
    hyphens, a RegExp with global flag should be possible.

    Any suggestions?

    --
    Rob
  • VK

    #2
    Re: RegExp for hyphen to camelCase?



    RobG wrote:[color=blue]
    > I'm messing with getPropertyValu e (Mozilla et al) and currentStyle (IE)
    > and have a general function (slightly modified from one originally
    > posted by Steve van Dongen) for getting style properties:
    >
    > function GetCurrentStyle ( el, prop ) {
    > if ( window.getCompu tedStyle ) {
    > // Mozilla et al
    > return window.getCompu tedStyle(el, '').getProperty Value(prop) );
    > } // IE5+
    > else if ( el.currentStyle ) {
    > return el.currentStyle[prop];
    > } // IE4
    > else if ( el.style ) {
    > return el.style[prop];
    > }
    > }
    >
    > If property names have no hyphen (e.g. width, height) then all is fine.
    > But with hyphenated names (e.g. margin-right, border-top) Mozilla
    > wants them unmodified and IE wants them camelCased (marginRight, borderTop).
    >
    > Is there a simple RegExp that will camelCase hyphenated strings? I can
    > do it with a loop and string operations but would prefer to use a single
    > RegExp if possible.
    >
    > The following works fine using substring (for s having 0 or more
    > hyphens) but is there a simpler way?
    >
    > function toCamel ( s ) {
    > s = s.split('-');
    > var i=0, j=s.length;
    > while ( ++i < j ) {
    > s[0] += s[i].substring(0,1) .toUpperCase() + s[i].substring(1);
    > }
    > return s[0];
    > }
    >
    > I've tried using RegExp but can't get a simple expression without
    > looping - property names have up to 3 (or more? three-d-light-shadow)
    > hyphens, a RegExp with global flag should be possible.
    >
    > Any suggestions?
    >
    > --[/color]


    The pattern search would be simple:

    var re = /(-)([a-z])/g;

    hyphenString.re place(re,"$2");

    This would transform "a-b-c" to "abc"

    Unfortunately back to NN4 they have forgotten to include in
    JavaScript's RegExp the case transformation sequences (\u and \U). And
    so far no one bothered to fix it. So there is no way to transform
    "a-b-c" to "aBC" other than using .exec method, pass through all
    matches and apply toUpperCase() with string re-assemply each time.

    In this case the old charAt/substring method *much* more time/ressource
    effective :-(

    Comment

    • Baconbutty

      #3
      Re: RegExp for hyphen to camelCase?

      I would agree with VK's comments.

      Taking from both your comments you could try this at least:-

      var s="three-d-light-shadow";
      var r=/(-)([a-z])/g;
      s=s.replace(r,f unction(a,b,c){ return c.toUpperCase() ;});
      alert(s);

      Comment

      • fox

        #4
        Re: RegExp for hyphen to camelCase?



        RobG wrote:[color=blue]
        >
        > I'm messing with getPropertyValu e (Mozilla et al) and currentStyle (IE)
        > and have a general function (slightly modified from one originally
        > posted by Steve van Dongen) for getting style properties:
        >
        > function GetCurrentStyle ( el, prop ) {
        > if ( window.getCompu tedStyle ) {
        > // Mozilla et al
        > return window.getCompu tedStyle(el, '').getProperty Value(prop) );
        > } // IE5+
        > else if ( el.currentStyle ) {
        > return el.currentStyle[prop];
        > } // IE4
        > else if ( el.style ) {
        > return el.style[prop];
        > }
        > }
        >
        > If property names have no hyphen (e.g. width, height) then all is fine.
        > But with hyphenated names (e.g. margin-right, border-top) Mozilla wants
        > them unmodified and IE wants them camelCased (marginRight, borderTop).
        >
        > Is there a simple RegExp that will camelCase hyphenated strings? I can
        > do it with a loop and string operations but would prefer to use a single
        > RegExp if possible.
        >
        > The following works fine using substring (for s having 0 or more
        > hyphens) but is there a simpler way?
        >
        > function toCamel ( s ) {
        > s = s.split('-');
        > var i=0, j=s.length;
        > while ( ++i < j ) {
        > s[0] += s[i].substring(0,1) .toUpperCase() + s[i].substring(1);
        > }
        > return s[0];
        > }
        >
        > I've tried using RegExp but can't get a simple expression without
        > looping - property names have up to 3 (or more? three-d-light-shadow)
        > hyphens, a RegExp with global flag should be possible.
        >
        > Any suggestions?
        >[/color]

        function
        toCamel(s)
        {
        var re = /(-)(\w)/g;

        return s.replace(re,
        function(fullma tch,paren1,pare n2)
        {
        return paren2.toUpperC ase();
        });
        }

        Comment

        • VK

          #5
          Re: RegExp for hyphen to camelCase?

          > var s="three-d-light-shadow";[color=blue]
          > var r=/(-)([a-z])/g;
          > s=s.replace(r,f unction(a,b,c){ return c.toUpperCase() ;});
          > alert(s);[/color]

          That's an absolutely cool twist!
          Flushing substring !

          Comment

          • Baconbutty

            #6
            Re: RegExp for hyphen to camelCase?

            It does enable you to be quite concise.

            Oddly though, I have found that if you use this type of technique on
            very large strings, it actually becomes much more inefficient than
            ordinary String concatenation or Array joining, by quite a margin. For
            a 200k string, String concatenation is about 10x faster. But for small
            Strings can be quite useful.

            Comment

            • VK

              #7
              Re: RegExp for hyphen to camelCase?

              > Oddly though, I have found that if you use this type of technique on[color=blue]
              > very large strings, it actually becomes much more inefficient than
              > ordinary String concatenation or Array joining, by quite a margin. For
              > a 200k string, String concatenation is about 10x faster.[/color]

              it's not so odd because regexp's are very resource intensive. So on big
              texts it takes *a lot*. In some serious implementations of regexp's
              there is study() method to "prepare" a large text for regexp
              processing.

              IE introduced re.compile() method to convert static regexp to binary
              code for maximum speed. Did you try that?

              Comment

              • Baconbutty

                #8
                Re: RegExp for hyphen to camelCase?

                >it's not so odd because regexp's are very resource intensive. So on big[color=blue]
                >texts it takes *a lot*.[/color]

                I can see how that would be.
                I suppose jumping out of the process to call a function will not help
                either.
                [color=blue]
                >IE introduced re.compile() method to convert static regexp to binary
                >code for maximum speed. Did you try that?[/color]

                No I didn't. I'll give it a try. Thanks.

                Comment

                • RobG

                  #9
                  Re: RegExp for hyphen to camelCase?

                  Baconbutty wrote:[color=blue]
                  > I would agree with VK's comments.
                  >
                  > Taking from both your comments you could try this at least:-
                  >
                  > var s="three-d-light-shadow";
                  > var r=/(-)([a-z])/g;
                  > s=s.replace(r,f unction(a,b,c){ return c.toUpperCase() ;});
                  > alert(s);
                  >[/color]

                  Cool, unfortunately Safari doesn't like it, returning:

                  threefunction (a, b, c)
                  {
                  return c.toUpperCase() ;
                  }function (a, b, c)
                  {
                  return c.toUpperCase() ;
                  }ightfunction (a, b, c)
                  {
                  return c.toUpperCase() ;
                  }hadow

                  It is returning the function body rather than the result - similarly
                  for Fox's suggestion.

                  So thanks, but I'll have to stick with looping for now. Hopefully
                  style property names will never reach 200k ;-)


                  --
                  Rob

                  Comment

                  • Michael Winter

                    #10
                    Re: RegExp for hyphen to camelCase?

                    On 21/07/2005 12:39, RobG wrote:
                    [color=blue]
                    > Baconbutty wrote:[/color]

                    [Use a function argument]
                    [color=blue]
                    > Cool, unfortunately Safari doesn't like it, [...]
                    >
                    > It is returning the function body rather than the result - similarly for
                    > Fox's suggestion.[/color]

                    So will IE5 and earlier as they don't support function arguments, and
                    Opera 6 won't perform a replacement at all (a no-op).
                    [color=blue]
                    > So thanks, but I'll have to stick with looping for now. [...][/color]

                    It takes about 2KB to replace the replace method. :)

                    Mike

                    --
                    Michael Winter
                    Prefix subject with [News] before replying by e-mail.

                    Comment

                    • Baconbutty

                      #11
                      Re: RegExp for hyphen to camelCase?

                      > Cool, unfortunately Safari doesn't like it,
                      [color=blue]
                      > Will IE5 and earlier as they don't support function arguments
                      > Opera 6 won't perform a replacement at all[/color]

                      Thats a shame. It is in the ECMA spec I think, but that is of course
                      no guarantee that it is implemented everywhere. .
                      [color=blue]
                      > It takes about 2KB to replace the replace method. :)[/color]

                      Perhaps the challenge then is to come up with the most concise
                      alternative. A starter:-

                      var a=s.split(""); var b=[]; var j=a.length; var i=0;
                      do {b[b.length]=(a[i]=="-")?a[++i].toUpperCase(): a[i];}while(++i<j)

                      Comment

                      • Martin Honnen

                        #12
                        Re: RegExp for hyphen to camelCase?



                        RobG wrote:

                        [color=blue]
                        > function GetCurrentStyle ( el, prop ) {
                        > if ( window.getCompu tedStyle ) {
                        > // Mozilla et al
                        > return window.getCompu tedStyle(el, '').getProperty Value(prop) );
                        > } // IE5+
                        > else if ( el.currentStyle ) {
                        > return el.currentStyle[prop];
                        > } // IE4
                        > else if ( el.style ) {
                        > return el.style[prop];
                        > }
                        > }
                        >
                        > If property names have no hyphen (e.g. width, height) then all is fine.
                        > But with hyphenated names (e.g. margin-right, border-top) Mozilla wants
                        > them unmodified and IE wants them camelCased (marginRight, borderTop).[/color]

                        getComputedStyl e is supposed to return an object implementing the
                        CSSStyleDeclara tion interface but that interface can optionally be
                        casted to the CSS2Properties interface which then allows accessing CSS
                        properties the same way you do with element.style in browsers e.g.
                        element.style.c ssPropertyName
                        so in Mozilla and Opera you can do
                        return window.getCompu tedStyle(el, '')[prop]
                        if the CSS property name is passed in in camel case (e.g.
                        'backgroundColo r', 'marginRight').
                        Could you test whether Safari allows that too?



                        --

                        Martin Honnen

                        Comment

                        • Michael Winter

                          #13
                          Re: RegExp for hyphen to camelCase?

                          On 21/07/2005 14:10, Martin Honnen wrote:

                          [snip]
                          [color=blue]
                          > so in Mozilla and Opera you can do
                          > return window.getCompu tedStyle(el, '')[prop][/color]

                          You could but the global object has never been defined as an instance of
                          the AbstractView interface. I would use the slightly longer, but
                          better defined route through the document object:

                          document.defaul tView.getComput edStyle(...)
                          [color=blue]
                          > if the CSS property name is passed in in camel case (e.g.
                          > 'backgroundColo r', 'marginRight').[/color]

                          Though you should be careful as there is an exception to the case
                          conversion pattern: float becomes cssFloat.
                          [color=blue]
                          > Could you test whether Safari allows that too?[/color]

                          Neither Safari nor Konqueror support the getComputedStyl e method. Though
                          it exists as a property of the defaultView object in Konqueror, it
                          always returns null.

                          Mike

                          --
                          Michael Winter
                          Prefix subject with [News] before replying by e-mail.

                          Comment

                          • Martin Honnen

                            #14
                            Re: RegExp for hyphen to camelCase?



                            Michael Winter wrote:
                            [color=blue]
                            > On 21/07/2005 14:10, Martin Honnen wrote:
                            >[color=green]
                            >> so in Mozilla and Opera you can do
                            >> return window.getCompu tedStyle(el, '')[prop][/color]
                            >
                            >
                            > You could but the global object has never been defined as an instance of
                            > the AbstractView interface. I would use the slightly longer, but better
                            > defined route through the document object:
                            >
                            > document.defaul tView.getComput edStyle(...)[/color]

                            Right, I was mainly following Rob's code and only changing the part
                            after the getComputedStyl e. I have myself pointed out that
                            document.defaul tView and window don't have to be the same as far as the
                            W3C DOM says but as far as Mozilla goes Brendan Eich himself said the
                            current behaviour is not going to be changed:
                            <http://groups-beta.google.com/group/netscape.public .mozilla.dom/msg/aa219bf41334c22 e?hl=en&>
                            And the current WHAT WG drafts also try to ensure that the current
                            praxis that browsers implement document.defaul tView as the window object
                            becomes standardized:
                            <http://www.whatwg.org/specs/web-apps/current-work/#documentwindow >
                            so it seems pretty safe to do window.getCompu tedStyle.

                            [color=blue]
                            > Neither Safari nor Konqueror support the getComputedStyl e method. Though
                            > it exists as a property of the defaultView object in Konqueror, it
                            > always returns null.[/color]

                            Ouch, one more case for not only checking for the existance of a method
                            in the DOM but to check for the result too.

                            --

                            Martin Honnen

                            Comment

                            • Lasse Reichstein Nielsen

                              #15
                              Re: RegExp for hyphen to camelCase?

                              "Baconbutty " <julian@baconbu tty.com> writes:
                              [color=blue]
                              > Perhaps the challenge then is to come up with the most concise
                              > alternative. A starter:-
                              >
                              > var a=s.split(""); var b=[]; var j=a.length; var i=0;
                              > do {b[b.length]=(a[i]=="-")?a[++i].toUpperCase(): a[i];}while(++i<j)[/color]

                              Overkill (mainly splitting the string into a character array and
                              looking at each char, not the total size of the snippet). Also
                              remember to join "b" afterwards.

                              Anyway:

                              var p=s.split("-"),i=p.leng th;
                              while(--i){p[i]=p[i].charAt(0).toUp perCase()+p[i].substring(1);}
                              s=p.join("");

                              /L
                              --
                              Lasse Reichstein Nielsen - lrn@hotpop.com
                              DHTML Death Colors: <URL:http://www.infimum.dk/HTML/rasterTriangleD OM.html>
                              'Faith without judgement merely degrades the spirit divine.'

                              Comment

                              Working...