views:

92

answers:

3

Hi!

I have this kind of HTML :

<h1> Text1 Text2 </h1>

I want via jquery to change this HTML in :

<h1> <span>Text1</span> Text2 </h1>

I my head is coming just append and regular expression (maybe you have another ideas ) , unfortunately I don't have experience with "regex" . The "Text1" is changeable .. It should be the first text in "h1" Can somebody help me !

Thanks !

A: 

get the text

var text = $('h2').text();
var $arr = text.split(' ');

now you have value in array, you can loop init or jsut use $arr[0] and $arr[1] to use it how ever you like it.

Basit
+1  A: 

The following will wrap the first word of the first h1 tag with a span tag.

$("h1").html($("h1").html().replace(/^\w+\b/, function(result) {
    return "<span>" + result + "</span>";
}));
Joel Potter
Text1 is going to change, it should be automatically the first word
Alexander Corotchi
Updated to match any word. `\w` matches word characters (letters, numbers and underscore). To get even more generic you could use `.` to match anything.
Joel Potter
+3  A: 

Assuming you want to wrap the first word of each H2 in a span, and the H2 is guaranteed to have no HTML tags inside, you'd do it as follows:

// For each H2.
$('h2').each(function() {
  // Get text.
  var text = $(this).text();
  // Split into words.
  var words = text.split(' ');
  // Wrap the first word.
  if (words.length > 0) words[0] = '<span>' + words[0] + '</span>';
  // Join the results into a single string.
  var result = words.join(' ');
  // Put the results back into the H2.
  $(this).html(result);
});

Or using regex:

// For each H2.
$('h2').each(function() {
  $(this).html($(this).text().replace(/^(\W*)\b(\w+)\b/, '$1<span>$2</span>'));
});
Max Shawabkeh
+1 for the $1, $2. I did not know you could do that.
Joel Potter
It is awesome !
Alexander Corotchi