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