#164 ✓not_for_core
Claudio Bertarelli

String userfull Functions

Reported by Claudio Bertarelli | June 12th, 2008 @ 08:53 PM

Object.extend(String.prototype, {
    left : function(n){
        if(n<=0){
            return "";
        } else if(n>this.length){
            return str;
        } else {
            return this.substring(0, n);
        }
    },
    right : function(n){
        if(n<=0){
           return "";
        }else if(n>this.length){
           return str;
        } else {
            return this.substring(this.length, this.length - n);
        }
    }
});

Comments and changes to this ticket

  • John-David Dalton

    John-David Dalton June 13th, 2008 @ 04:26 AM

    • State changed from “new” to “enhancement”
  • Juriy Zaytsev

    Juriy Zaytsev June 13th, 2008 @ 11:11 PM

    Could you explain when this is useful?

    Both #left and #right are almost identical to a native String.prototype.slice, except that #slice actually knows how to deal with negative argument ;)

    String.prototype.left = function(n) {
      return n<=0 ? "" : this.slice(0,n);
    }
    
    String.prototype.right = function(n) {
      return n<=0 ? "" : this.slice(-n);
    }
    
  • Claudio Bertarelli

    Claudio Bertarelli June 24th, 2008 @ 03:46 PM

    I use to ZeroFill a number

    and use as my Unique ID

        var GlobalIndex = 1;
        myUID = ('000' + GlobalIndex).right(3);
    
  • Tobie Langel

    Tobie Langel June 30th, 2008 @ 04:44 PM

    • State changed from “enhancement” to “not_for_core”
    • Tag cleared.

    These are too app specific imho.

    Furthermore, for your particular use case, I'd advise using Number#toPaddedString.

    (255).toPaddedString(4)
    // -> "0255"
    

Please Sign in or create a free account to add a new ticket.

With your very own profile, you can contribute to projects, track your activity, watch tickets, receive and update tickets through your email and much more.

New-ticket Create new ticket

Create your profile

Help contribute to this project by taking a few moments to create your personal profile. Create your profile ยป

The Prototype JavaScript library.

Shared Ticket Bins

Pages