Reputation: 785
I have a div with the following content, for instance:
<div id="x">Lorem ipsum dolor sit amet.</div>
I want to be able to dynamically, through JavaScript, bold ipsum
and then amet
, for example, so the new text looks like this:
Lorem **ipsum** dolor sit **amet**.
The JavaScript code that I have can do this, but only once at a time. When I call toBold("ipsum")
and then toBold("amen")
, the function will only bold met
. The function will only bold the argument in the last function call.
var haystackText = document.getElementById('x').innerHTML;
var replaced = "";
function toBold (y) {
var match = new RegExp(y, "ig");
var boldText = "<div style=\"display: inline; font-weight: bold;\">" + y + "</div>";
replaced = haystackText.replace(match, boldText);
document.getElementById('x').innerHTML = replaced;
}
How can I change this function so that both "ipsum" and "amet" are bolded?
Thank you for the help
Upvotes: 0
Views: 73
Reputation: 1084
Working Fiddle: https://jsfiddle.net/w01tzoux/
JavaScript
function toBold(targetString) {
var original = document.getElementById('x').innerHTML;
var replaced = original.replace(targetString, "<b>" + targetString + "</b>");
document.getElementById('x').innerHTML = replaced;
}
toBold ("ipsum");
toBold ("amet");
Upvotes: 0
Reputation: 1
One approach could be to pass an array to toBold
, using "(" + y.join(")|(") + ")"
as RegExp
; utilizing replacement
function of .replace()
to set each captured word
var haystackText = document.getElementById('x').innerHTML;
var replaced = "";
function toBold(y) {
var match = new RegExp("(" + y.join(")|(") + ")", "gi");
replaced = haystackText.replace(match, function(match) {
return "<div style=\"display: inline; font-weight: bold;\">"
+ match
+ "</div>";
});
document.getElementById('x').innerHTML = replaced;
}
toBold(["ipsum", "amet"])
<div id="x">Lorem ipsum dolor sit amet.</div>
Upvotes: 0
Reputation: 21575
While there are problems with this method (as @epascarello mentioned), but the main problem here is that haystackText
was never updated, and will always use the original value:
function toBold (y) {
var match = new RegExp(y, "ig");
var boldText = "<div style=\"display: inline; font-weight: bold;\">" + y + "</div>";
replaced = haystackText.replace(match, boldText);
haystackText = replaced;
document.getElementById('x').innerHTML = replaced;
}
Also as I noted in a comment you can also use <b>
or <strong>
instead for bolding. Here is a fiddle example.
Upvotes: 1