简体   繁体   中英

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".

<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 id="test">tree_and_house</textarea>

I was thinking to start with val.replace, but how can I remove whole line?

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

You can split on newline character \\n and filter out those which contains the word cat . Also you need to re-set the value attribute, which you're currently not doing.

$('#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. jQuery has its own replace function: $.replaceWith().

I would also advice the online regeular expression tester , which works like a charm and gives very useful feedback.

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.

Hope it helps.

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

return:

tree_and_house

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

return:

//empty row 
//empty row
tree_and_house

If you need case sensitive match remove i :

/^.*car.*/gm

this not match Car or cAr

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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