第一个和第二个名字首字母,保留完整姓氏

时间:2018-02-07 13:05:46

标签: javascript jquery

这是我第一次使用javascript,我真的需要帮助。我有一个带有div的html,每个包含一到三个“作者”文本值。如果div中有多个“author”,我需要自动缩短名称(只有名字)。 例如

<div class="book">
        <a> <h2>Book 1</h2>
        <h3 class="author">Minty Estelle</h3>
        <h3 class="author">Katey Josepha Shevon</h3></a></div>

<div class="book">
        <a> <h2>Book 2</h2>
        <h3 class="author">Leila Seward</h3></a></div>

所以输出将是:

Book 1 
M. Estelle  
K.J. Shevon

Book 2 
Leila Seward

因此,如果只有一个“作者” - 他的名字保持不变。但如果它不止一个 - 名字和名字(但不是姓氏 - 最后一个值)缩短为第一个字母,然后是点。

我搜索了一个lor并玩了编辑...但没有任何效果。有人可以帮忙找到解决方案吗? 到目前为止我的js是:

    var authorName = $(".book h3");
  authorName.each(function(){
  if(authorName.length > 1 && authorName.hasClass("author")){
    var names = authorName.split(" ");
    var shortened = names.not(:lastChild).map(s => s.slice(0, 1).append(". "));
    document.authorName.innerHTML = shortened;
  }

2 个答案:

答案 0 :(得分:0)

你必须遍历你的书籍,然后遍历所述书的每位作者:

//For each book
$('.book').each(function() {
  //If the book has more than one author
  if ($('h3.author', this).length > 1) {
    //For each author
    $('h3.author', this).each(function() {
      //Store the author name before emptying it
      var words = $(this).text().split(' ');
      $(this).text('');

      //For each word inside the author name
      for (var i = 0; i < words.length; i++) {
        //If it's not the last name
        if (i < words.length - 1) {
          //Only keep the first letter
          $(this).text($(this).text() + words[i].substring(0, 1) + '. ');
        //Else keep the whole word
        } else $(this).text($(this).text() + words[i]);
      }
    });
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="book">
  <a>
    <h2>Book 1</h2>
    <h3 class="author">Minty Estelle</h3>
    <h3 class="author">Katey Josepha Shevon</h3>
  </a>
</div>

<div class="book">
  <a>
    <h2>Book 2</h2>
    <h3 class="author">Leila Seward</h3>
  </a>
</div>

答案 1 :(得分:0)

这是一个简单的版本,根据自己的需要调整它,并且可能将其重构为更具功能性的方式:)

/*
So that output would be:

Book 1 
M. Estelle  
K.J. Shevon

Book 2 
Leila Seward*/
$(".book").each(function() {

  var authors = $('h3.author', this);

  if (authors.length > 1) {
    authors.each(function() {

    var result = $(this).text().split(' ').map(function(name, index, arr) {
      return index < arr.length - 1 ? name[0]+'.' : name;
    }).join(' ');

    $(this).text(result);
   });
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.0/jquery.min.js"></script>
<div class="book">
        <a> <h2>Book 1</h2>
        <h3 class="author">Minty Estelle</h3>
        <h3 class="author">Katey Josepha Shevon</h3></a></div>

<div class="book">
        <a> <h2>Book 2</h2>
        <h3 class="author">Leila Seward</h3></a></div>