JQuery matches the first letter in a string and the wrapper with a span tag

I am trying to get the first letter in a paragraph and wrap it with a <span> . Notice that I said the letter, not the symbol, as I deal with dirty markup, which often has spaces.

Existing markup (which I cannot 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 to ignore anything other than /[a-zA-Z]/ ? Any help would be greatly appreciated.

+4
source share
5 answers
 $('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/

+4
source

I would vote against using JS for this task. This will make your page slower and also bad practice to use JS for presentation purposes.

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

+4
source

Matt Ball's solution is good, but if you have a paragraph and an image or markup or quotation marks, the regular expression will not just fail, but break the html for example

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

You can avoid html hacking in these cases by adding "'<to the selected start characters. Although in this case there will be no range wrapped on the first character.

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

I think that Optimally you can wrap the first character after "or" However, I believe that it is better not to wrap the character if it is already in the markup, but this probably requires a second replacement.

+3
source

I don't seem to have permission to answer the answer, so forgive me for that. The answer given by Matt Ball will not work if P contains another element as the first child. Go to the violin and add IMG (very often), since the first child is from P, and I from Img will turn into a drop.

+1
source

If you use the x parameter (not sure if it is supported in jQuery), you can leave the script space in the template. Then use something like this:

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

You know in what format your first character should be, and he should capture only this character in a group. If you can have characters other than spaces before your first letter, maybe something like this:

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

Conditionally, first catch other characters, and then transfer the first letter to the group, which you could then wrap around the span tag.

-1
source

All Articles