tobiasg tobiasg - 8 months ago 50
HTML Question

Replace string in textarea on click and then copy (jQuery)

I have this form with a

and a
. If someone enters a text in the textarea and clicks the button, I want the function to search for if "Tobias" was entered in the textarea and if so, replace it with "Hanna" and finally copy it to the clipboard.

If I enter this in the textarea...

Tobias is great!

...and then click the button; I want this to be copied to the clipboard:

Hanna is great!

But it won't work. This is the code so far:

var $textArea = $("textarea");
var $newText = $textArea.val().replace("Tobias", "Hanna");

Answer Source

You can't do a .select() on a string. As per the documentation, its use is limited to <input type="text"> and <textarea> elements.

Perhaps what you're looking for is something like this:

    var $textArea = $("textarea");
    var oldText = $textArea.val();
    var newText = oldText.replace("Tobias","Hanna");

This changes the textarea value to the replacement text, copies it, and then changes it back, all without the user knowing.

Additionally as a friendly note... While there is nothing syntactically incorrect with your $newText variable, I'd personally suggest dropping the $ from its name.

When working with a block of jQuery code, those familiar with the language will most likely assume that a variable prefixed with $ refers to a jQuery object/array. In your case, $newText is a basic string, so it's quite deceiving.