开发者

Insert text before and after the selected text with jQuery

开发者 https://www.devze.com 2023-02-06 01:45 出处:网络
I want to put some specified text (where possible) before and after any selec开发者_运维问答ted text in an HTML document.

I want to put some specified text (where possible) before and after any selec开发者_运维问答ted text in an HTML document.

I think there should be a smart way to do that with jQuery. Is there anyway to insert specific text before and after selected text anywhere in the document using jQuery?


Well, here's one way to do it (though I suspect there are more concise, efficient and, honestly, better ways of doing it):

var needle = 'ipsum';
var wrappingText = ' wrapper ';

$('p').each(
    function(){
        var haystack = $(this).text();
        $(this).text(haystack.replace(needle, wrappingText + needle + wrappingText));
    });

This, obviously, relies upon the text being contained within a p element, but that's easily amended to any other particular element, or class of element.

JS Fiddle demo

And here's a way of wrapping the needle with html (though, again, it's probably not the prettiest way):

html:

<form action="" method="post">
    <fieldset>
        <label for="needle">Search for this text: </label>
        <input type="text" name="needle" id="needle" placeholder="Example: 'sit'" />
    </fieldset>
    <fieldset>
        <label for="wrapper">Wrap with this:</label>
        <input id="wrapper" name="wrapper" type="text" placeholder="Example: <em>" />
    </fieldset>
    <fieldset id="choose">
        <input type="radio" name="wrapWith" id="text" value="0" checked /><label for="html">Text</label>
        <input type="radio" name="wrapWith" id="html" value="1" /><label for="html">HTML</label>
    </fieldset>
    <fieldset>
        <input type="submit" value="search" />
    </fieldset>
</form>

<p>Lorem ipsum dolor sit amet.</p>
<p>Lorem ipsum dolor sit amet.</p>

jQuery:

$('form').submit(
    function(){
        var needle, wrapper, haystack;
        if ($('#needle').val().length >= 1) {
          needle = $('#needle').val();  
        }
        else {
            needle = 'ipsum';
        }

        if ($('#wrapper').val().length >= 1) {
            wrapper = $('#wrapper').val();
        }
        else {
            wrapper = 'wrap';
        }

        var wrappingText = 'wrapper';
        $('p').each(
            function(){
                if ($('#text').is(':checked')) {
                    haystack = $(this).text();
                    $(this).text(haystack.replace(needle, wrapper + needle + wrapper));
                }
                else if ($('#html').is(':checked')) {
                    haystack = $(this).text();
                    $(this).html(haystack.replace(needle, wrapper + needle + wrapper.replace('<', '</')));
                }
            });
        return false;
    });

JS Fiddle demo.

0

精彩评论

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

关注公众号