Biomehanika
Biomehanika

Reputation: 1540

jQuery find and replace text

I have a text contained on a <textarea> like this:

Hi {nom},

We are glad to accept your invitation.

I need it to become

Hi Dolly Parton,

We are glad to accept your invitation.

I don't want to use any plugin, but I have tried developing this simple functionality with no possitive result:

prevContent=$('textarea').val(); //alerts correctly textarea content
content = prevContent.replace('{nom}','Dolly Parton');

In this case, no replacement is made and content has the same value as prevContent.

This is not meant to make a real time replacemet, it has to be replaced before submitting form:

 $(document).on('click','.submitMessage', function(){
        prevContent=$('textarea').val();    
        content = prevContent.replace('{nom}','Dolly Parton');

        $.post('../actions/newMessage.php',{ms_content:content}).success(

                    function(data){
                        alert("yikes");}
   );}
});

SOLVED: This was due to a spell mistake on variable. It was sent like {nom1}, not {nom}. Sorry for the inconvenience.

Upvotes: 2

Views: 96

Answers (2)

Oleksandr T.
Oleksandr T.

Reputation: 77482

You need use RegExp with g flag, because in your example only first {nom} will be replaced:

var prevContent = $('textarea').val();
var content     = prevContent.replace(/\{nom\}/g, 'Dolly Parton');

and to update textarea you can use .val, like so

$('textarea').val(content);

Example

Upvotes: 7

VikrantMore
VikrantMore

Reputation: 903

You will just need to assign value of "content" to textarea, as :

$('textarea').val(content);

Upvotes: 0

Related Questions