使用javascript从文本区域删除包含特定单词的行

时间:2017-05-22 11:04:53

标签: javascript textarea

我正在尝试使用textarea中的javascript删除包含特定单词的行。

这是示例

www.youtube.com/watch?v=CxPh1tgiK2g&index=0&list=PLB03EA9545DD188C3
www.youtube.com/watch?v=xOYPv7CxMVk&index=1&list=PLB03EA9545DD188C3
www.youtube.com/watch?v=kKC7-ACrs1w&index=2&list=PLB03EA9545DD188C3
www.youtube.com/watch?v=qE2EuZZCMYE&index=3&list=PLB03EA9545DD188C3

如果用户在输入字段中输入值,则应删除包含它的行。假设用户输入CxPh1tgiK2gxOYPv7CxMVk,应删除包含这些ID的行

3 个答案:

答案 0 :(得分:1)

尝试

$("#remove").click(function() {
  var text = $("#id").val()

  var lines = $('#textarea').val().split('\n');

  lines = lines.filter(function(val) {
    if (val.match(text)) return false
    else return true

  })
  
  $('#textarea').text(lines.join('\n'))

})

$("#replace").click(function() {
  var text = $("#id").val()

  var lines = $('#textarea').val().split('\n');

  var n = Math.floor(Math.random()*lines.length)
  lines[n] = lines[n].replace(/\?v=([A-Za-z0-9]){11}/, "?v="+text)
  
  $('#textarea').text(lines.join('\n'))

})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<input type="text" id="id" />
<input type="button" id="remove" value="Remove" />
<input type="button" id="replace" value="Replace" />
<br/>

<textarea id="textarea" rows="4" cols="150">
www.youtube.com/watch?v=CxPh1tgiK2g&index=0&list=PLB03EA9545DD188C3
www.youtube.com/watch?v=xOYPv7CxMVk&index=1&list=PLB03EA9545DD188C3
www.youtube.com/watch?v=kKC7-ACrs1w&index=2&list=PLB03EA9545DD188C3
www.youtube.com/watch?v=qE2EuZZCMYE&index=3&list=PLB03EA9545DD188C3
</textarea>

答案 1 :(得分:0)

作为删除包含行的解决方案

var value = test.value.split(/\n/g).filter(function(val)
{
  return val !== "";
});
console.log(value);
setTimeout(function()
{
   var index = value.findIndex(function(val)
   {
     return val.includes('kKC7-ACrs1w');
   });
   if (index !== -1)
   {
     value.splice(index, 1);
     test.value = value.join("\n");
   }
}, 2000);
.text {
  width: 100%;
  resize: none;
  height: 200px;
}
Line with <b>kKC7-ACrs1w </b>will be removed in 2 secs
<textarea name="" id="test" class=text >
www.youtube.com/watch?v=CxPh1tgiK2g&index=0&list=PLB03EA9545DD188C3
www.youtube.com/watch?v=xOYPv7CxMVk&index=1&list=PLB03EA9545DD188C3
www.youtube.com/watch?v=kKC7-ACrs1w&index=2&list=PLB03EA9545DD188C3
www.youtube.com/watch?v=qE2EuZZCMYE&index=3&list=PLB03EA9545DD188C3
</textarea>

答案 2 :(得分:0)

您可以这样做:

var ta = document.querySelector("textarea");
var lines = ta.innerHTML.split("\n");
var id = "omg";

for (var i = 0; i < lines.length; i ++) {
  if (lines[i].indexOf(id) > -1) {
    lines.splice(i, 1);    
  }
}

ta.innerHTML = lines.join("\n");
<textarea>
lol
omg
js
</textarea>