【问题标题】:Hashtag to a normal TextHashtag 到普通文本
【发布时间】:2019-01-01 07:14:37
【问题描述】:

如何将主题标签转换为普通文本?

例如:

<div class="hashtag">Hello #my_best_friend, you are #welcome</div>

结果: 你好,我最好的朋友,不客气

【问题讨论】:

  • console.log($('.hashtag').first().html().replace(/#/g, ''));
  • @RavishaHesh 不会删除下划线。
  • console.log($('.hashtag').first().html().replace(/#/g, '').replace('/_/g', ' '));

标签: jquery hashtag


【解决方案1】:

您可以尝试在 RegExps 的帮助下使用 String#replace 替换不需要的字符:

$('.hashtag').each(function() {
  var text = $(this).text();

  $(this).text(
    text
    .replace(/#(\w+)/g, '$1')
    .replace(/_/g, ' ')
  );
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="hashtag">Hello #my_best_friend, you are #welcome</div>

【讨论】:

    【解决方案2】:

    如果您的浏览器支持零宽度肯定后向断言,那么您可以使用以下正则表达式将井号标签中不需要的符号替换为空格:

    var src = $('.hashtag').text();
    $('.hashtag').text(src.replace(/((^|\s)#(?=\S+)|(?<=#\S+)_)/g, ' '))
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <div class="hashtag">Hello #my_best_friend, you are #welcome</div>

    【讨论】:

    • 是的!有用。谢谢亚历山大。如果我想包装主题标签怎么办,所以我得到这个:
      你好我最好的朋友,你是欢迎
      跨度>
    • @AbdelkaderBenkhaled,那么你必须使用.html() 方法而不是.text() 和另一个正则表达式。您可以使用regex101.com 构建自己的表达式
    【解决方案3】:

    请查看这两个页面:jQuery's replaceWith() 和 Javascript 的 replace()

    $(document).ready(function() {
      var string = $('.hashtag').html();  // get the content
      var result = string.replace("#my_best_friend", "my best friend");  // replace keywords
      $('.hashtag').replaceWith( result );  // update the content
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-05-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-12-03
      • 1970-01-01
      • 1970-01-01
      • 2015-01-30
      相关资源
      最近更新 更多