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

JavaScript substring from begin to first space - Stack Overflow

programmeradmin1浏览0评论
const title=document.title;
const id = title.substring(0,title.indexOf(' '));

Can these two lines be more concise? What is the best practice to get substring from begin to first space

const title=document.title;
const id = title.substring(0,title.indexOf(' '));

Can these two lines be more concise? What is the best practice to get substring from begin to first space

Share asked Jan 7, 2018 at 8:16 bilabilabilabila 1,1631 gold badge13 silver badges20 bronze badges 5
  • 3 "Best practice" is, sometimes, quite subjective. But, regarding the code golf, this wins: title.split(" ")[0] – Gerardo Furtado Commented Jan 7, 2018 at 8:19
  • By default indexOf returns the position of the first appearance of the searching string is available. – Tung Commented Jan 7, 2018 at 8:20
  • 3 @GerardoFurtado technically title.split` `[0] wins the code golf – Patrick Roberts Commented Jan 7, 2018 at 8:42
  • @PatrickRoberts Yes, it does! – Gerardo Furtado Commented Jan 7, 2018 at 8:47
  • I would argue split is probably what most people would want in this case. If there is no space it will still work, str = 'Prince'; str.substring(0, str.indexOf(' ')) will not. – user128511 Commented Jan 7, 2018 at 10:30
Add a ment  | 

2 Answers 2

Reset to default 6

Reference split method

You can using split() method

const id = title.split(' ')[0]

You can use the split() function. The split function breaks the whole string in the form of array. In the code give below, the variable title contains string 'Muhammad Usman', so the function split() breaks the string in the form or an array in 'id' variable. Therefore the 0-th index of id, id[0] contains the value 'Muhammad' & index 1 of id id[1] contains the value 'Usman'.

I'm attaching the output of the code which prints the first string before the space.

<html>
   <body>
      <script language="javascript" type="text/javascript">

     const title="Muhammad Usman";

     const id=title.split(' ')[0];
     document.write("id :" + id);

      </script>
   </body>
</html>

发布评论

评论列表(0)

  1. 暂无评论