2

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

<p>Metuentes igitur idem latrones Lycaoniam magna parte campestrem</p>

So now if the user search for a string, I want it to be highlighted (we use a bold tag for example)

<p>Metuentes igitur idem latrones <b>Lycaoniam</b> magna parte campestrem</p>

And then we can revert back to original string if needed.

  1. The first question is whether we can select a substring like this using jQuery, and use jQuery method such as .css() to apply style to that element.
  2. The second question is if we don't have such selector, how can we achieve it using jQuery or javascript through string manipulation

Thanks.

UPDATED

Thank for everyone effort. Here is a small program, final result of what I'm looking for http://jsfiddle.net/TPg9p/3/ Cheers!

Thanh Trung
  • 3,566
  • 3
  • 31
  • 42
  • I don't think jQuery can select the sub-string as it is not a html element. You could select the p element, and then use .html() to get the current string, manipulate that string in JavaScript adding in a and tag where needed, then setting the html of the p again using .html(newHtmlVariable). – user1573618 Nov 18 '13 at 13:41

5 Answers5

2

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.

Cranio
  • 9,647
  • 4
  • 35
  • 55
1

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/

Community
  • 1
  • 1
silicakes
  • 6,364
  • 3
  • 28
  • 39
1

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/.

  • Shouldn't it be `/Lycaoniam/gi` ? – Thanh Trung Nov 18 '13 at 13:49
  • That's quite long for a regexp string. Could you explain a bit what it matches? And why `$&` but not `$1` or `$number` – Thanh Trung Nov 18 '13 at 13:58
  • @ThanhTrung For the long regex see : http://stackoverflow.com/a/3561711/1636522. For `$&` see : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace. –  Nov 18 '13 at 14:00
  • Not work => http://jsfiddle.net/GeyvD/1/ I think the original string has to be escaped first – Thanh Trung Nov 18 '13 at 14:13
  • @ThanhTrung I guess you have to escape backslashes. I've added a demo : http://jsfiddle.net/wared/TPg9p/. –  Nov 18 '13 at 14:29
1

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

Md Ashaduzzaman
  • 4,032
  • 2
  • 18
  • 34
0

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.

Hugo Tunius
  • 2,869
  • 24
  • 32
  • We don't know in advance which string the user is searching for so it's useless to wrap a span around a word in advance – Thanh Trung Nov 18 '13 at 13:48
  • In addition, toggleClass would remove the class but not the span. And the span, if I got the OP's intentions right, should not be present in the beginning. I've posted above what I think is a better solution. – Cranio Nov 18 '13 at 13:52
  • Yupp absolutely, my solution is based on knowing beforehand what element should be able to be highligthed. I will leave the answer here if someone else has a similar problem where my solution is applicable. – Hugo Tunius Nov 18 '13 at 13:56