开发者

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

开发者 https://www.devze.com 2023-03-20 23:43 出处:网络
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开发者_StackOverflow中文版 often h

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开发者_StackOverflow中文版 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.


$('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/


I would vote against using JS for this task. It'll make your page slower and also it's a bad practice to use JS for presentation purposes.

Instead I can suggest using :first-letter pseudo-class to assign additional styles to the first letter in paragraph. Here is the demo: http://jsfiddle.net/e4XY2/. It should work in all modern browsers except IE7.


Matt Ball's solution is good but if you paragraph has and image or markup or quotes the regex will not just fail but break the html for instance

<p><strong>Important</strong></p>
    or
<p>"Important"</p>

You can avoid breaking the html in these cases by adding "'< to the exuded initial characters. Though in this case there will be no span wrapped on the first character.

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

I think Optimally you may wish to wrap the first character after a ' or " I would however consider it best to not wrap the character if it was already in markup, but that probably requires a second replace trial.


I do not seem to have permission to reply to an answer so forgive me for doing it like this. The answer given by Matt Ball will not work if the P contains another element as first child. Go to the fiddle and add a IMG (very common) as first child of the P and the I from Img will turn into a drop cap.


If you use the x parameter (not sure if it's supported in jQuery), you can have the script ignore whitespace in the pattern. Then use something like this:

/^([a-zA-Z]).*$/

You know what format your first character should be, and it should grab only that character into a group. If you could have other characters other than whitespace before your first letter, maybe something like this:

/.*?([a-zA-Z]).*/

Conditionally catch other characters first, and then capture the first letter into a group, which you could then wrap around a span tag.

0

精彩评论

暂无评论...
验证码 换一张
取 消