如何删除span中的连字符?(jQuery)

How to remove hyphen in span? (jQuery)

本文关键字:连字符 jQuery span 删除 何删除      更新时间:2023-09-26

我有在特定链接中生成连字符的面包屑。

<div class="breadcrumbs">
   <span class="home">
        <a href="#"><span property="name">Home</span></a>
   </span>
   <span>
        <a href="#" class="post post-vehicle-archive"><span property="name">books-for-sale</span></a>
   </span>
   <span>
        <a href="#" class="book-name"><span property="name">Soup for the sould</span></a>
   </span>
</div>

我想删除class="post post vehicle archive"中的炒作。

这是我迄今为止尝试的代码:

<script type="text/javascript">
    var j = jQuery.noConflict();
    j(function() {
        var getTermName = j('.breadcrumbs .post.post-type-archeive > span');
        j(getTermName ).text(value.replace(/'-/g, " "));
    });
</script>

结果应该是"待售图书"

感谢您的帮助。

尝试使用.text() 的接收器功能

var getTermName = j('.breadcrumbs .post.post-type-archeive > span');
getTermName.text(function(i,value) {
  return value.replace(/'-/g, " ")
});

如果您想将文本更改为标题大小写,请使用以下代码,

var getTermName = j('.breadcrumbs .post.post-type-archeive > span');
getTermName.text(function(i,value) {
  return value.replace(/'-/g, " ").split(" ").map(function(function(val){
     return val.charAt(0).toUpperCase() + val.slice(1);
  }).join(" ");
});

或者不要让事情变得太复杂,

JS:

var getTermName = j('.breadcrumbs .post.post-type-archeive > span').addClass("titleCase");
getTermName.text(function (i, value) {
    return value.replace(/'-/g, " ")
});

CSS:

.titleCase {
    text-transform: capitalize;
}

使用text()回调来更新所有元素的innerText。

  1. 在所有的面包屑上反复
  2. 删除连字符,并使每个单词的第一个字符大写

var j = jQuery.noConflict();
j(function() {
  // This will loop over all the matched `<a>` elements
  // Corrected selector
  j('.breadcrumbs span a').text(function(i, oldText) {
    //     To capitalize the first character of first word
    return oldText[0].toUpperCase() + oldText.substring(1).replace(/-[a-z]/g, function(m) {
      // Add space and capitalize the first character
      return ' ' + m[1].toUpperCase();
    });
  });
});
a {
  margin: 5px;
  text-decoration: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="breadcrumbs">
  <span class="home">
    <a href="#"><span property="name">Home</span>
  </a>
  </span>
  <span>
    <a href="#" class="post post-vehicle-archive"><span property="name">books-for-sale</span>
  </a>
  </span>
  <span>
    <a href="#" class="book-name"><span property="name">Soup for the sould</span>
  </a>
  </span>
</div>

Regex解释:

  1. -:从字面上匹配连字符。在字符类外部使用时无需转义
  2. [a-z]:匹配单个小写字母
  3. g:全局标志,用于匹配所有可能的匹配项

注意:如果您也想将分隔的空间的面包屑大写,请使用以下regex

/[-'s][a-z]/g