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/
$('div.message').text(function(i,txt) {
var name = $('div.name').text().split(' ')[ 0 ];
return txt.replace( 'friend', name );
});
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/
$('div.message').text(function(i,txt) {
var name = $.trim($('div.name').text()).split(' ')[0];
return txt.replace( 'friend', name );
});
You might wanna try this function, this works if you are not sure if the word is friend or foe or something else for as long as it is the second word that you wanted to replace. Just call this javascript function within your page... In my sample I added a link to call the script. Don't forget to include the jquery library.
<div class="name">Bob Marley</div>
<div class="message">Hey friend, how are you?</div>
<a onclick="demoMatchClick()">Change</a>
<script type="text/javascript">
function ReplaceSecondWord() {
var strRegExp = new RegExp('Hey (.+), how are you?');
var strCurrentText = $(".message").html();
var strName = $(".name").html().split(" ");
strCurrentText = strCurrentText.replace(strCurrentText.match(strRegExp)[1], strName[0]);
$(".message").html(strCurrentText);
}
</script>
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