最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

jquery - the best way to remove the first char of a given string in javascript - Stack Overflow

programmeradmin1浏览0评论

Using jquery, underscore or pure javascript what is the best way to remove the first char of a given string?

I will make something like this:

"aamerica".substring(1,"aamerica".length);

"aamerica".slice(1);

Is better to use slice or substring?

Using jquery, underscore or pure javascript what is the best way to remove the first char of a given string?

I will make something like this:

"aamerica".substring(1,"aamerica".length);

"aamerica".slice(1);

Is better to use slice or substring?

Share Improve this question edited Oct 12, 2012 at 20:24 Lorraine Bernard asked Oct 12, 2012 at 20:16 Lorraine BernardLorraine Bernard 13.4k23 gold badges85 silver badges137 bronze badges 1
  • 1 Um... that is the best way. What is wrong with that approach? Could be wrapped in a function if you do it a lot. – Jeremy J Starcher Commented Oct 12, 2012 at 20:18
Add a comment  | 

4 Answers 4

Reset to default 13

You would actually be fine doing:

"aamerica".substring(1);

EXAMPLE

substring's second parameter is optional:

string.substring(indexA[, indexB])

"aamerica".substring(1);

your "aamerica".length; is unecessary

quote from doc:

string.substring(indexA[, indexB])

If indexB is omitted, substring extracts characters to the end of the string.

You are in total 3 options:

  • "aamerica".substring(1);
  • "aamerica".slice(1);
  • "aamerica".substr(1);

All three methods have equivalent performance.

You can use slice: "aamerica".slice(1);

You can't do it much better than you already are.

You can, however, omit the 2nd parameter when you want your substring to go to the end of the string.

var s = "aamerica".substring(1);

发布评论

评论列表(0)

  1. 暂无评论