1

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 !

3 Answers 3

3

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>'));
});
Sign up to request clarification or add additional context in comments.

Comments

1

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>";
}));

2 Comments

Text1 is going to change, it should be automatically the first word
Updated to match any word. \w matches word characters (letters, numbers and underscore). To get even more generic you could use . to match anything.
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.