2

i have string need to be wrapped by tag HTML with conditional like this:

<h1>Test</h1>

Then nothing will happen

<h1>Test Lagi</h1>

Then the first word will be wrapped by span, result <h1><span>Test</span> Lagi</h1>

<h1>Test Lagi ah</h1>

Then only the first word will be wrapper by span, result:

<h1><span>Test</span> Lagi ah</h1>

How to do that in jQuery?

3
  • Please don't use signatures. Also, there may be a somewhat related question and solution over here: stackoverflow.com/questions/3760085/… Commented Sep 24, 2011 at 18:07
  • it's wrong to saying thank you @_@ Commented Sep 24, 2011 at 18:22
  • 1
    @JIP, I'm not against a "thank you" as a sign off, just pointing out that the OP also included a signature, which the FAQ frowns upon. Commented Sep 24, 2011 at 18:24

4 Answers 4

2

After following CoryLarson's link Here is a better solution: http://jsfiddle.net/avmFe/

$(function(){
    $('h1').each(function(){
       var me = $(this);
        if(/(\W+)/.test(me.html())) {
          me.html(me.html().replace(/^(\w+)/, '<span>$1</span>'));
        }
    });
});

Hope it helps.

Sign up to request clarification or add additional context in comments.

Comments

2
$(function(){
    $('h1').each(function(){
        var txt = $(this).text();
        var wordArray = txt.split(' ');

        var new_first = '<span>'+wordArray[0]+'</span>';
        var new_txt = txt .replace("wordArray[0]",new_first);
        $(this).html(new_txt);

    });
});

Comments

0

http://jsfiddle.net/Rs4TA/1/

$('*:contains("Test")').html('<span>Test</span>'); 

If your "test" is a static text, it could be done by this way.

1 Comment

word test is not static word.
-1

This does it: http://jsfiddle.net/RE9rp/1/

And here's the JS:

function wrapFirstWord($el, word){
    $el.each(function(){
        var txt = $(this).text();
        var wordArray = txt.split(' ');
        if(wordArray[0] === word && wordArray.length > 1){
            var newHTML = '<span>' + word + '</span>';
            for(var i = 1; i < wordArray.length; i++){
                newHTML += ' ' + wordArray[i];
            }
            $(this).html(newHTML);
        }
    });
}

$(function(){
    wrapFirstWord($('h1'),'Test');
});

You simply pass to wrapFirstWord() the set of elements you want to check for the word ($el), as well as the word you are looking for.

4 Comments

im sorry, i mean word test is only for testing purpose not the real implementation. The first word can be test, morning, afternoon
Does that mean that you want something that will wrap any first word? Or you want to be able to pass the chosen word to the function as an argument?
i want something that wrap the first word
See my updated fiddle/code. This will let you accomplish the task with any word and for any element.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.