jQuery删除重复的主题标签

时间:2017-04-16 13:30:51

标签: javascript jquery regex

我正在尝试使用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>

2 个答案:

答案 0 :(得分:1)

您可以做的一件事是,在#拆分并从数组中删除重复项,然后再次使用#加入数组..通过执行以下操作:

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

Demo

答案 1 :(得分:1)

您可以像这样修改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将是左边的条目。包含确保一切都是小写的代码应该很容易,如果这就是你要找的东西。

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