1

I have a div of text. I want to highlight some of this text stored in a variable using RegExp and span. the text to be highlighted is unknown at run time.

var t = $("#highlightOutput").html(); //sentence
	var s = t.search(hStr);//what shd be replaced
	var query = new RegExp(s, "g");
	console.log(s);
	t = t.replace(query, "<span class='highlight'>"+s+ "</span>"); //problem is here
	//how to write a regex code to highlight text stored in s.
	$("#highlightOutput").html(t);

1 Answer 1

1

search returns an index, but you want actual text. Use match for that: this method returns an array of matches, and you can take the first one.

var s = t.match(hStr)[0];
Sign up to request clarification or add additional context in comments.

Comments

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.