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.
- 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. - 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!
If you know the element in which to search:
for more elements, simply loop through them and do the replacing. To make a toggable styling, I'd use a custom class:
and remove it with:
.contents().unwrap() does the trick of stripping not only the class (which must be styled accordingly) but also the tag.
Based on the answer from here: Wrap around part of text inside an element
you could do the following:
http://jsfiddle.net/YxMvq/
Search for the text and replace the text.
HTML :
jQuery :
Demo
There is no way to do this with pure jQuery. You could do this instead :
To revert back to the original text :
The
search.replace(...)
part allows to deal with special chars : http://jsfiddle.net/wared/TPg9p/.Do you know when the HTML is created which word you want? Then I would suggest doing the following instead
now if you wanna highlight it just do
Any styles can be defined in the
highligthed
class. You could also use anid
for the span instead if you want to be able to apply the change to only that single element and not all elements withjs-highlightable
class.