/    Sign up×
Community /Pin to ProfileBookmark

string must have specific length

I want the value of a variable to always have 6 characters. If it has less, I want zero’s added to the end, and if it has more I just want the end of it cut off. Any suggestions on how to do it?

to post a comment
JavaScript

4 Comments(s)

Copy linkTweet thisAlerts:
@heavenly_blueauthorAug 03.2004 — would this work for if it's less than 6 characters long?

[CODE]
while (theVariable.length < 6){theVariable = theVariable + "0";}
[/CODE]
Copy linkTweet thisAlerts:
@heavenly_blueauthorAug 03.2004 — and possibly this for the other?

[CODE]
if (theVariable.length > 6){theVariable.length = 6;}
[/CODE]


i'm just making this up as i go along, but it looks like it might work.
Copy linkTweet thisAlerts:
@JonaAug 03.2004 — [font=trebuchet ms]Quite surely, it is, for the first.[/font]
Copy linkTweet thisAlerts:
@JonaAug 03.2004 — [font=trebuchet ms]For the second, use the following.[/font]

<i>
</i>&lt;script type="text/javascrpit"&gt;
var k = "This is more than six";
if(k.length &gt; 6){
k = k.substr(0, 6);
}
alert(k);
&lt;/script&gt;
×

Success!

Help @heavenly_blue spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 5.28,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @AriseFacilitySolutions09,
tipped: article
amount: 1000 SATS,

tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,
)...