the best way to remove the first char of a given string in javascript

戏子无情 提交于 2019-12-12 14:59:09

问题


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?


回答1:


You would actually be fine doing:

"aamerica".substring(1);

EXAMPLE

substring's second parameter is optional:

string.substring(indexA[, indexB])




回答2:


"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.




回答3:


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




回答4:


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);



来源:https://stackoverflow.com/questions/12866477/the-best-way-to-remove-the-first-char-of-a-given-string-in-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!