【问题标题】:jQuery remove duplicated hashtagjQuery 删除重复的标签
【发布时间】:2017-04-16 23:18:23
【问题描述】:

我正在尝试使用 jQuery 制作主题标签系统,但我的代码有问题。所以通常代码工作正常。但我想删除书面主题标签中的重复标签。

我在 codepen.io 上创建了这个 DEMO

在此演示中,当您编写内容并按空格键时,# 会自动添加到单词前面。我不希望用户能够将同一个单词写两次,例如:#abc #Abc #aBc #abC #ABC

我使用正则表达式创建了这段代码,但它不起作用。

// Remove duplicated hashatgs.
  text = text.replace(/[#]{2,}/gi, function removeHashtags(x) { return '#'; });

这里是完整的代码:

// Move cursor to the end.
function placeCaretAtEnd(el) {
    el.focus();
    if (typeof window.getSelection != "undefined"
            && typeof document.createRange != "undefined") {
        var range = document.createRange();
        range.selectNodeContents(el);
        range.collapse(false);
        var sel = window.getSelection();
        sel.removeAllRanges();
        sel.addRange(range);
    } else if (typeof document.body.createTextRange != "undefined") {
        var textRange = document.body.createTextRange();
        textRange.moveToElementText(el);
        textRange.collapse(false);
        textRange.select();
    }
}


// Add hashtags on each word.
function addHashtags(text) {
  // Add hashtag.
  text = text.replace(/([\w]+)/gi, function addHashtag(x){ return '#' + x; });
  // Remove duplicated hashatgs.
  text = text.replace(/[#]{2,}/gi, function removeHashtags(x) { return '#'; });
  // Prevent double spaces  
  text = text.replace(/  /g, ' ');
   
  text = text.trim();
  // return results
  return text;
}


// Convert characters to charCode
function toCharCode(char) { return char.charCodeAt(0); }


// Define special characters:
var characters = new Set([
  0, 32, // space
  13, // enter
  // add other punctuation symbols or keys
]);


var forbiddenCharacters = new Set([
  toCharCode("_"),
  toCharCode("-"),
  toCharCode("?"),
  toCharCode("*"),
  toCharCode("\\"),
  toCharCode("/"),
  toCharCode("("),
  toCharCode(")"),
  toCharCode("="),
  toCharCode("&"),
  toCharCode("%"),
  toCharCode("+"),
  toCharCode("^"),
  toCharCode("#"),
  toCharCode("'"),
  toCharCode("<"),
  toCharCode("|"),
  toCharCode(">"),
  toCharCode("."),
  toCharCode(","),
  toCharCode(";")
]);



$(document).ready(function() {
  var element = '#text';

  $(element).keypress(function (e) {
    if (characters.has(e.keyCode)) {
      // Get and modify text.
      var text = $(element).text();
      text = addHashtags(text);
      // Save content.
      $(element).text(text);
      // Move cursor to the end
      placeCaretAtEnd(document.querySelector(element));
    } else if (forbiddenCharacters.has(e.keyCode)) {
      e.preventDefault();
    }
  });
});
.container {
   position:relative;
   width:100%;
   max-width:600px;
   overflow:hidden;
   padding:10px;
   margin:0px auto;
   margin-top:50px;
}
* {
   box-sizing:border-box;
   -webkit-box-sizing:border-box;
   -moz-box-sizing:border-box;
}
.addiez {
   position:relative;
   width:100%;
   padding:30px;
   border:1px solid #d8dbdf;
   outline:none;
   font-family: helvetica, arial, sans-serif;
   -moz-osx-font-smoothing: grayscale;
   -webkit-font-smoothing: antialiased;
}
.addiez::-webkit-input-placeholder {
   /* Chrome/Opera/Safari */
   color: rgb(0, 0, 1);
}
.addiez[contentEditable=true]:empty:not(:focus):before  {
      content:attr(placeholder);
      color: #444;
    }

.note {
   position:relative;
   width:100%;
   padding:30px;
   font-weight:300;
   font-family: helvetica, arial, sans-serif;
   -moz-osx-font-smoothing: grayscale;
   -webkit-font-smoothing: antialiased;
   line-height:1.8rem;
   font-size:13px;
}
.ad_text {
   position:relative;
   width:100%;
   padding:10px 30px;
   overflow:hidden;
   font-weight:300;
   font-family: helvetica, arial, sans-serif;
   -moz-osx-font-smoothing: grayscale;
   -webkit-font-smoothing: antialiased;
   line-height:1.8rem;
   font-size:13px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
   <div class="addiez" contenteditable="true" id="text" placeholder="Write something with space"></div>
   <div class="ad_text" id="ad_text"></div>

【问题讨论】:

    标签: javascript jquery regex


    【解决方案1】:

    您可以做的一件事是,在# 处拆分并从数组中删除重复项,然后再次使用# 加入数组.. 这样做:

    var unique = text.replace(/\s/g,'').split('#').filter(function(elem, index, self) {
    return index == self.indexOf(elem.replace('\s+$',''));
    })
    text = unique.join(" #");
    

    Demo

    【讨论】:

      【解决方案2】:

      您可以像这样修改 AddHashtags 函数:

      // Add hashtags on each word.
      function addHashtags(text) {
          // Add hashtag.
          text = text.replace(/([\w]+)/gi, function addHashtag(x){ return '#' + x; });
      
          // Remove duplicated words
          text = text.replace(/\b(\w+)\b(?=.*\b\1\b)/gi, function removeDuplicates(x) { return ''; });
      
          // Prevent single/double hashtags
          text = text.replace(/[#]{2,}/gi, function removeDoubleHashtags(x) { return '#'; });
          text = text.replace(/[#]{1}\s+/gi, function removeSingleHashtags(x) { return ''; });
      
          // Prevent double spaces  
          text = text.replace(/  /g, ' ');
          text = text.trim();
      
          // return results
          return text;
      }
      

      如果有重复的单词,它将覆盖原始条目,所以如果列表看起来像:#hashtag #HaSHtag,那么#HaSHtag 将是剩下的条目。包含代码以确保所有内容都是小写的应该很容易,如果这是您正在寻找的。​​p>

      删除列表中重复单词的正则表达式来自这个 SO 答案:https://stackoverflow.com/a/16406260/6909765

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2011-12-01
        • 1970-01-01
        • 2019-11-15
        • 2012-01-05
        • 2011-10-27
        • 2012-05-29
        • 2016-01-30
        相关资源
        最近更新 更多