Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

First Word in String with jquery

Tags:

jquery

string

I'm trying to figure out function that will help me wrap first word in string into span.

But unfortunately no luck.

Can anyone help me please?

Many Thanks

Dom

like image 279
Dom Avatar asked Sep 21 '10 12:09

Dom


2 Answers

One way:

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

[ source | try it ]

Basically, for each match (something) you replace the first word with itself ($1) wrapped in <span> tags. The character class \w matches letters, digits, and underscores (thus defining what a "word" is - you may need another definition).

like image 189
jensgram Avatar answered Oct 09 '22 20:10

jensgram


You ask how to do that in jQuery. I think you'll need a regular expression to litteraly add the span.

Here is an example using jQuery to get a text from the DOM and make the update in the DOM after having added the span to the string with a regular expression.

<div id="container">This is the text</div>
<script type="text/javascript">
jQuery(function($){
    // get the text you want to transform in a variable
    var html = $('#container').html();
    // doing the transformation (adding the span) with a regular expression
    html = html.replace(/^([^\s]*)(.*)/, "<span class=\"first-word\">$1</span>$2");
    // update your text
    $('#container').html(html);

    // or in one line:
    $('#container').html( ('#container').html().replace(/^([^\s]*)(.*)/, "<span class=\"first-word\">$1</span>$2") );
});
</script>

This is what you'll get:

<div id="container"><span class="first-word">This</span> is the text</div>
like image 37
Ben Avatar answered Oct 09 '22 21:10

Ben