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!

1
  • 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 <b> and </b> tag where needed, then setting the html of the p again using .html(newHtmlVariable). Commented Nov 18, 2013 at 13:41

5 Answers 5

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.

Sign up to request clarification or add additional context in comments.

3 Comments

+1 for using unwrap trick. We don't need to store the original value!
Yes but I made a mistake, my code would substitute only the 1st occurrence. Now it should be ok with a RegExp :)
This works in the given case, but will fail if the search string contains regexp string
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/.

5 Comments

Shouldn't it be /Lycaoniam/gi ?
That's quite long for a regexp string. Could you explain a bit what it matches? And why $& but not $1 or $number
Not work => jsfiddle.net/GeyvD/1 I think the original string has to be escaped first
@ThanhTrung I guess you have to escape backslashes. I've added a demo : jsfiddle.net/wared/TPg9p.
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/

2 Comments

No, that's not string selector. You don't get my question
This works in the given case, but will fail if the search string contains regexp string
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

1 Comment

This will replace only 1st occurrence.
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.

3 Comments

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.