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.
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, " "));
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With