简体   繁体   English

从文本区域中删除所有包含特定单词的行

[英]Remove all lines from textarea contains specific word

I have textarea with text in few lines. 我有几行文字的文本区域。 I want to remove lines contains specific word, for example "car". 我要删除包含特定单词的行,例如“ car”。

<textarea id="test">cars_and_house
tree_and_car
tree_and_house
cat_and_car</textarea>

To make textarea looks like that (without empty lines): 要使textarea看起来像这样(没有空行):

<textarea id="test">tree_and_house</textarea>

I was thinking to start with val.replace, but how can I remove whole line? 我本来想从val.replace开始,但是如何删除整行?

$( "#test" ).val().replace("car", "") ;

You can split on newline character \\n and filter out those which contains the word cat . 您可以分割换行符\\n并过滤掉包含单词cat的字符。 Also you need to re-set the value attribute, which you're currently not doing. 另外,您需要重新设置您当前不使用的value属性。

$('#test').val(function(_, val){
   return val.split("\n").filter(function(line){
      return line && line.indexOf("car") == -1
   }).join("\n");
});

What you are using is the good old vanilla javascript replace function. 您正在使用的是旧的老式javascript替换功能。 jQuery has its own replace function: $.replaceWith(). jQuery有自己的替换功能:$ .replaceWith()。

I would also advice the online regeular expression tester , which works like a charm and gives very useful feedback. 我还建议在线regeular表达测试仪 ,它的工作原理很吸引人 ,并给出了非常有用的反馈。

I think this snippet will work for you: 我认为此代码段将为您工作:

var newValue = $("#test").val().replace(/([\w]?)*car([\w]?)*/gi,"");
$("#test").val(newValue);

where g searches for more than the first match, and i makes it case insensitive. 其中, g搜索的内容比第一个匹配项还多,而使其不区分大小写。

Hope it helps. 希望能帮助到你。

This: $( "#test" ).val().replace(/^.*car.*\\n?/gim,""); 这是: $( "#test" ).val().replace(/^.*car.*\\n?/gim,"");

return: 返回:

tree_and_house

This: $( "#test" ).val().replace(/^.*car.*/gim,""); 这: $( "#test" ).val().replace(/^.*car.*/gim,"");

return: 返回:

//empty row 
//empty row
tree_and_house

If you need case sensitive match remove i : 如果您需要case sensitive匹配项,请删除i

/^.*car.*/gm

this not match Car or cAr 这不匹配CarcAr

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM