Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace a single letter wrap with span element using jquery

I need to replace the first letter in the div content and wrap it with a <span> tag.

Here is my html:

<div class="first_ltr">
    <p>This is a Test </p>
</div>

I want to replace the html in the form of:

<div class="first_ltr">
    <p><span>T</span>his is a Test </p>
</div>

I tried:

$(".first_ltr").each(function () {
    var currentText = $(this).html();
    $(this).text(currentText.replace("0","<span></span>"));
});

Can any one help? Thanks in advance for help.

like image 906
Arun Avatar asked Mar 30 '15 11:03

Arun


4 Answers

You can pass to .html callback, and add any tag to text, like so

$('.first_ltr p').html(function (index, html) {
  return '<span>' + html.slice(0, 1) + '</span>' + html.slice(1);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="first_ltr">
  <p>This is a Test </p>
</div>

html.slice(0, 1) - returns first letter in string

html.slice(1) - returns string without first letter

Update I've written small plugin, you can try it

$.fn.wrapText = function (tag, position) {
    var $contaiter = $('<div />');

    this.html(function (index, html) {
        var start = position;
            end   = position + 1;

        if (position > html.length) {
            position = 0;
        }

        $contaiter.html($('<' + tag + '/>').html(html.slice(start, end)));

        return [html.slice(0, start), $contaiter.html(), html.slice(end)].join('');
    });
};

$('.first_ltr p').wrapText('span', 0);
$('.last_ltr p').wrapText('div', 13);

Example

like image 68
Oleksandr T. Avatar answered Nov 15 '22 12:11

Oleksandr T.


Not the shortest solution, but it works with every text:

var $span = $('<span />');
$(".first_ltr > p").each(function(){
    var firstLetter = $(this).text().slice(0,1); //find first letter
    var text = $(this).text().slice(1); //find rest of the text 
    $span.text(firstLetter); //wrap first letter in span-tag
    $(this).text(text); //override old text
    $(this).prepend($span); //prepend first letter
});

Demo

like image 43
empiric Avatar answered Nov 15 '22 13:11

empiric


Something like this should work for you.

var text = $('.first_ltr p').text();
var split = text.split('');
var firstLetter = split[0];
var rest = split.splice(1,split.length)
$('.first_ltr p').html('<span>' + firstLetter +'</span>' + rest.join(''));

https://jsfiddle.net/d1pf6cjy/1/

like image 42
rjmacarthy Avatar answered Nov 15 '22 11:11

rjmacarthy


Here is a posible solution:

$(document).ready(function(){
    var myText = $('.first_ltr > p').text();
    var start = '<span>' + myText.slice(0,1) + '</span>';
    var end = myText.slice(1, myText.length);
    $('.first_ltr > p').html(start + end);
});

Demo: http://jsfiddle.net/r2zp2vqm/1/

Hope it's helps!

like image 29
gon250 Avatar answered Nov 15 '22 11:11

gon250