Assuming regex is the best way to do this , I would like to select the first word of :
<div class="name">Bob Marley</div>
and use it to replace the second word in in this div tag:
<div class="message">Hey friend, how are you?</div>
So that the end result equals :
<div class="message">Hey Bob, how are you?</div>
Update
This is a medley of my actual code here. I noticed that when this runs, it just puts the jquery text into my text area rather than actually perform the function. This is probably because I’m drawing from inputs which requre val() and not text in div tags like my above examples suggest.
$(".me_signup .name").bind("mouseup keyup", function(){
$(this).siblings('.message').text(function(i,txt) {
var name = $(this).val().split(' ')[0];
return txt.replace('friend', name);
});
});
This creates a text area with this written in it
function (i, txt) {
var name = $(this).val().split(" ")[0];
return txt.replace("friend", name);
}
You should be able to get by without a regex.
Example: http://jsfiddle.net/2R5kA/
If there’s a chance that there may be some leading spaces before the name, then use jQuery’s
$.trim()method it first.Example: http://jsfiddle.net/2R5kA/1/