Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

first 2 characters of a string 1

Status
Not open for further replies.

jamert

Programmer
Dec 9, 2007
80
CA
how whould one get the first 2 characters of a string? thanks

var d = "asdfasdfasdfasdf";
if (d.length>2)
{
get first 2 characters here
}
 
jamert, this is a complete SW post but I figured I'd post it as an alternative to the above solution since it's what I always use.

The substring method requires 2 parameters. The position of the first character in the string to pull, and the position of the last character in the string to pull. However, at a glance I've always found the substring method to be confusing. In marouanemeft's example above, it will return the first 2 characters in the string variable d. However, if you look at the parameters passed (0 and 1), there is only a difference of 1. Again, at a glance I find this confusing because I would expect it to only return 1 character (because of the difference between the two parameters).

Thankfully ECMA has provided us with an alternative. The substr method accepts 2 parameters as well - the position of the first character in the string, and the length of the substring you wish to pull. So, to modify marouanemeft's example to use the substr method:
Code:
d.[!]substr([/!]0, 2[!])[/!]

At a glance this is more intuitive. You know immediately how long the substring will be that is returned.

-kaht

Lisa, if you don't like your job you don't strike. You just go in every day and do it really half-assed. That's the American way. - Homer Simpson

[small]<P> <B> <P> <B> <P> <B> <P> <B> <P> <B> <P> <B> <P> <B> <P> <B> <P> <B> <P> <B> <P> <B> <P> <B> <P> <B> <P> <.</B>[/small]
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top