0

How do I trim all letter after the first letter?

e.g

var name = "Tony";
//output T
G.D
  • 181
  • 7
  • Clarify "letter". What is the expected output of "1a2b3" ? – Thilo Oct 28 '15 at 10:01
  • @Thilo he has clearly expressed the expected output in the comment – shennan Oct 28 '15 at 10:08
  • 1
    @shennan: In that example, all characters happen to be letters (no digits, no interpunctation, no space, etc). That makes it a bit ambiguous, which is why I am asking. – Thilo Oct 28 '15 at 10:10
  • @Thilo Ah, sorry. Temporary blindness. I didn't see your "la2b3" example. I thought you were just asking "What is the expected output?". – shennan Oct 28 '15 at 10:47

1 Answers1

2

This not called a trim, this is a simple substring :

console.log(name.substring(0, 1));

As suggested, you can also do

console.log(name[0]);

But this one will not works on old internet explorers (< IE7). This one will works everywhere too :

console.log(name.charAt(0));
DrunkWolf
  • 994
  • 1
  • 6
  • 18
Magus
  • 14,796
  • 3
  • 36
  • 51
  • 1
    Or even simpler, name[0] – DrunkWolf Oct 28 '15 at 10:00
  • 2
    @DrunkWolf I would prefer name.charAt(0), as bracket notation is not supported in some older browsers. See [this answer](http://stackoverflow.com/a/5943760/726766). – shennan Oct 28 '15 at 10:03
  • @shennan I find it hard to believe some people still concern themselves with IE7, seeing as it has a market share of <0.2%, but fair enough :) – DrunkWolf Oct 28 '15 at 10:04
  • 1
    @DrunkWolf True, but it's also more readable. There is no mistaking `name` for an object or an array. When there's no pain involved, I don't see the problem with supporting older browsers. – shennan Oct 28 '15 at 10:06
  • @shennan I wholeheartedly agree that there is no problem supporting older browers, but if the variable name is descriptive enough (like name is) we don't really have the problem with mistaking it for something it clearly isn't. If you regularly name objects or arrays 'name', you should seriously consider naming your variables better. That said, i upvoted your comment, as it's a legitimate consideration to make. I would personally go for name[0] myself, unless there was a chance i would be assigning values to the first character later on. – DrunkWolf Oct 28 '15 at 10:10
  • @DrunkWolf And I up-voted your original comment before considering it from the angle of browser support and readability. I don't think this needs to be an extended discussion. The benefits of each approach are clear to readers now. – shennan Oct 28 '15 at 10:42