2017-08-08 140 views
1

在这个网站上的一些人的帮助下,我设法在这里创建了一个hashtag计数器 - https://codepen.io/timothycdavis17/pen/ZJeVBj删除Textarea中的重复文本

这是代码。

HTML

<section class="section-textarea bg-primary"> 

    <div class="container"> 
    <div class="row"> 
     <div class="col-lg-12"> 
     <div class="well textarea-well clearfix"> 
      <textarea rows="16" class="form-control"></textarea> 

      <div class="buttons"> 
      <div class="btn-group" role="group" aria-label="Basic example"> 

      <button type="button" class="btn btn-secondary btn-primary btn-lg 
      count-button">Count</button> 

      <button type="button" class="btn btn-secondary btn-danger btn-lg 
      reset-button">Reset</button> 

      </div> 

     </div> 

      <div class="remaining-counter">Hashtags Counted:&nbsp;&nbsp;<span 
      class="well text-well">0</span></div> 


    </div> 

</div> 

</div> 

</div> 

</section> 

CSS

body { 
    background: #0275D8; 
} 

.textarea-well { 
    color: #000; 
    text-align: center; 
    margin: 10% auto; 
} 

textarea { 

    margin-bottom: 20px; 

} 

.text-well { 
    background: lightblue; 
} 

.count-button { 
    margin-bottom: 20px; 
} 

.remaining-counter { 
    font-size: 30px; 
    margin-bottom: 20px; 
} 

jQuery的

$(".count-button").click(function() { 
    var text = $("textarea").val(); 
    var count = (text.match(/(^|\W)(#[a-z\d A-Z\D][\w-]*)/g) || []).length; 
    $('.text-well').html(count); 

    var seen = {}; 
    $('textarea').each(function() { 
    var txt = $(this).text(); 
    if (seen[txt]) 
     $(this).remove(); 
    else 
     seen[txt] = true; 
    }); 

}).trigger('click'); 


$(".reset-button").click(function() { 
$("textarea").val(' '); 
$('.text-well').html(0); 
}).trigger('click'); 

有人提出有人问我后W不管它是否可能不会计入任何重复的标签输入textarea,并可能错误下划线与红色波浪线主题。

我已经看过这个网站的答案,但似乎无法找到一个工作。

任何帮助表示赞赏。

回答

1

只需使用临时数组来过滤重复项。

// save the matches instead of immediately counting 
var tags = text.match(/(^|\W)(#[a-z\d A-Z\D][\w-]*)/g) || []; 
// init empty array for holding unique matches 
var uTags = []; 
// loop through matches 
$.each(tags, function(index, value){ 
    // if match is not in holding array array, add it to holding array 
    if(uTags.indexOf(value) == -1) uTags.push(value); 
}); 
// get count from holding array which will only have one copy of each match 
var count = uTags.length; 

Here is a fork of your codepen with the above code.

+0

非常感谢,有没有办法样式重复的文字显示这是一个重复的用户? –

+0

当然,添加一个else块到if语句并添加你想运行的代码重复发现 – amflare

+0

我试图添加一个else语句,但并不完全确定我在做什么要诚实。我已经更新了我的代码簿 –