Chris Brauckmuller Chris Brauckmuller - 5 months ago 42
jQuery Question

jQuery match first letter in a string and wrap with span tag

I'm trying to get the first letter in a paragraph and wrap it with a

<span>
tag. Notice I said letter and not character, as I'm dealing with messy markup that often has blank spaces.

Existing markup (which I can't edit):

<p> Actual text starts after a few blank spaces.</p>


Desired result:

<p> <span class="big-cap">A</span>ctual text starts after a few blank spaces.</p>


How do I ignore anything but
/[a-zA-Z]/
? Any help would be greatly appreciated.

Answer
$('p').html(function (i, html)
{
    return html.replace(/^[^a-zA-Z]*([a-zA-Z])/g, '<span class="big-cap">$1</span>');
});

Demo: http://jsfiddle.net/mattball/t3DNY/