substring selector with jquery?

后端 未结 5 1090
南笙
南笙 2021-01-23 01:02

Is it possible to select only part of a string using jquery? For example I have a text

Metuentes igitur idem latrones Lycaoniam magna parte campestrem&l

相关标签:
5条回答
  • 2021-01-23 01:21

    There is no way to do this with pure jQuery. You could do this instead :

    var search = 'Lycaoniam';
    var orig = $('p').html();
    var highlighted = orig.replace(new RegExp(
        search.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&'), 'gi'
    ), '<b>$&</b>');
    $('p').html(highlighted);
    

    To revert back to the original text :

    $('p').html(orig);
    

    The search.replace(...) part allows to deal with special chars : http://jsfiddle.net/wared/TPg9p/.

    0 讨论(0)
  • 2021-01-23 01:21

    If you know the element in which to search:

    var string = "Lycaoniam";
    var e = $("elementSelector"); // put here your selector
    e.html(e.html().replace(new RegExp(search, "gi"), "<b>"+search+"</b>"));
    

    for more elements, simply loop through them and do the replacing. To make a toggable styling, I'd use a custom class:

     e.html(e.html().replace(new RegExp(search, "gi"), "<span class='highlight'>"+search+"</span>"));
    

    and remove it with:

    $(".highlight").contents().unwrap();
    

    .contents().unwrap() does the trick of stripping not only the class (which must be styled accordingly) but also the tag.

    0 讨论(0)
  • 2021-01-23 01:28

    Do you know when the HTML is created which word you want? Then I would suggest doing the following instead

    <p>Metuentes igitur idem latrones <span class="js-highlightable">Lycaoniam</span> magna parte campestrem</p>`
    

    now if you wanna highlight it just do

    $(".js-highlightable").toggleClass("highlighted"); 
    

    Any styles can be defined in the highligthed class. You could also use an id for the span instead if you want to be able to apply the change to only that single element and not all elements with js-highlightable class.

    0 讨论(0)
  • 2021-01-23 01:29

    Based on the answer from here: Wrap around part of text inside an element

    you could do the following:

    $('p').html(function(index, oldHtml){
       return oldHtml.replace(/(amet)/g, '<span>$1</span>');
    });
    

    http://jsfiddle.net/YxMvq/

    0 讨论(0)
  • 2021-01-23 01:31

    Search for the text and replace the text.

    HTML :

    <p id="mainText">Metuentes igitur idem latrones Lycaoniam magna parte campestrem</p>
    <input type="text" id="inputTextBox" />
    <input type="button" id="findButton" value="Find" />
    

    jQuery :

    $("#findButton").click(function(){
        var inputText = $("#inputTextBox").val();
        var mainText = $("#mainText").text();
        var updatedText = "<b>" + inputText + "</b>";
        mainText = mainText.replace(inputText, updatedText);
        $("#mainText").html(mainText);
    });
    

    Demo

    0 讨论(0)
提交回复
热议问题