简体   繁体   中英

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.

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

check below code . check DEMO

First option

 $(".first_ltr").each(function () {
    var currentText = $.trim($(this).text());
    var firstChar = currentText.charAt(0);
    currentText = currentText.substring(1, currentText.length);
   $(this).find('p').html('<span>'+firstChar+'</span>'+currentText);
 });

second option using slice check DEMO

  $(".first_ltr").each(function () {
     var currentText = $.trim($(this).text()); 
     $(this).find('p').html('<span>'+currentText.slice(0,1)+'</span>'+currentText.slice(1));
  });

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

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/

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!

Here is a solution that is in pure JavaScript. It is longer than the other answers, but that is mostly because it also covers more cases than just OP's simple example.

I've compiled a JSFiddle with some samples to show how it works. The fiddle uses a slight variation of this code that also allows specifying the wrapper element.

It basically travels the DOM tree using standard DOM API and tries to locate the first text node. The text node is validated with a regex to ensure that there is a letter to wrap in it. If not, it will go to the next text node until a suitable one is found. This approach means that the solution is independent of the underlying HTML structure, but should still be efficient.

You can easily adapt the regex to your liking. For example, you can wrap other characters than letters, wrap the entire first word ( [a-zA-Z]+ ), wrap a specific word, etc.

 var wrapFirst = function(nodes, letters) { var rgx = new RegExp("^([\\\\s\\\\S]*?)(" + letters + ")"); for (var i = 0; i < nodes.length; ++i) { // 1) Find the first text node var root = nodes[i]; var n = root.firstChild; var txt; while (n) { // Text node? if (n.nodeType == Node.TEXT_NODE) { if ((txt = n.data.match(rgx))) { break; } // Non-text node with children? } else if (n.firstChild) { n = n.firstChild; continue; } // Has next sibling? if (n.nextSibling) { n = n.nextSibling; // Parent has next sibling? } else if (n.parentNode !== root) { n = n.parentNode.nextSibling; // Nothing useful found } else { n = undefined; } } // 2) Wrap the text if (n) { // Remove char from the old text n.data = n.data.substring(txt[0].length); // Add the span (+prefix if any) var p = n.parentNode; if (txt[1]) { p.insertBefore(document.createTextNode(txt[1]), n); } var wr = document.createElement("span"); wr.appendChild(document.createTextNode(txt[2])); p.insertBefore(wr, n); } } } wrapFirst( document.getElementsByClassName("first_ltr"), "[a-zA-Z]" ); 
 span { background: yellow; } 
 <div class="first_ltr"> <p>This is a Test </p> </div> 

For a version that uses jQuery, you can look at the previous version of this answer (at the bottom, not the broken code at the top). It gives the same result, but may a bit less efficient (due to jQuery, but also by having to do more overall regex checks).

Use This:

Prepend method of Jquery

$( ".first_ltr" ).prepend( "<span>T</span>" );

Click Here For more Info

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM