Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replacing an exact text from textarea

I have this little problem with jQuery. I want to remove an specific text from textarea. Check my codes:

Textarea values:

aa

a

aaa 

i tried this:

$("#id_list").val($("#id_list").val().replace("a", " "));

The codes above only works if the text in each line is unique with no matching characters from other lines. Now the problem is the codes above removes the first letter from aa, instead of removing the second line a. How can I get it to work in replace/removing an exact word on a line from textarea? Any help would be much appreciated.

like image 688
Clyde Avatar asked Apr 03 '14 12:04

Clyde


2 Answers

Use word boundary.

Do this:

$("#id_list").val($("#id_list").val().replace(/\ba\b/g, " "));

That will replace only a

If you want to replace just one time, remove g from my regex.

If you want to use strings stored in a variable, do this:

var word = "a";
var regex = new RegExp("\\b"+word+"\\b","g");
$("#id_list").val($("#id_list").val().replace(regex, " "));
like image 140
Amit Joki Avatar answered Oct 02 '22 03:10

Amit Joki


Just use replace(/a/g, " ")) instead. the /g flag means you search globally for the "a" letter. Without it you just replace the first occurrence.

like image 30
Natalia Avatar answered Oct 02 '22 03:10

Natalia