Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to select the second word with jQuery and Regex..?

Tags:

jquery

regex

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);
}
like image 935
Trip Avatar asked Nov 09 '10 13:11

Trip


2 Answers

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 );
});
like image 157
user113716 Avatar answered Oct 22 '22 00:10

user113716


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>
like image 29
Carls Jr. Avatar answered Oct 22 '22 00:10

Carls Jr.