如果最后一个字符是某个字符,如何将其包装在元素中?

时间:2018-11-21 20:41:40

标签: javascript jquery

我对此来来回回,但我想我是如此亲近。我想用.content类将所有H1标签的最后一个字符包装起来,如果它是句号或问号(以应用颜色)。这是我所拥有的:

$(function() {
    $('.content h1').each(function() {
        last = $(this).text().trim().slice(-1);
        if(last === '.' || last === '?') {
            alert(last);
            //last.wrap('<span class="orange-end"></span>');
        }
    });
});

这将正确提示最后一个字符,我正努力换行并返回。

全力以赴。

1 个答案:

答案 0 :(得分:2)

$(function() {
    $('.content h1').each(function() {
      // get the text
      var text = this.innerHTML.trim();
      
      //do logic if the last character is a period or question mark
      if (['.', '?'].indexOf(text.slice(-1)) > -1) {
        // set the html back to what it was, replacing the last 
        // character with the wrapped html
        this.innerHTML = text.slice(0, -1) 
                       + '<span class="orange-end">'
                       + text.slice(-1)
                       + '</span>'; 
      }
    });
});
.orange-end { color: orange; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="content">
  <h1>What is the meaning of this?</h1>
  <h1>No way!</h1>
  <h1>I know.</h1>
</div>