Clyde
Clyde

Reputation: 79

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.

Upvotes: 5

Views: 199

Answers (3)

Furquan Khan
Furquan Khan

Reputation: 1594

You need to use regex replace

replace(/a/g, " "))

Upvotes: 1

Amit Joki
Amit Joki

Reputation: 59232

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, " "));

Upvotes: 4

Natalia
Natalia

Reputation: 308

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.

Upvotes: 2

Related Questions