user1008724
user1008724

Reputation: 73

Make HTML text bold

I wrote this function which takes in a word as input and puts it in a <b> tag so that it would be bold when rendered in HTML. But when it actually does get rendered, the word is not bold, but only has the <b> tag arround it.

Here is the function:

function delimiter(input, value) {
    return input.replace(new RegExp('(\\b)(' + value + ')(\\b)','ig'), '$1<b>$2</b>$3');
}

On providing the value and input, e.g. "message" and "This is a test message":

The output is: This is a test <b>message</b>
The desired output is: This is a test message

Even replacing the value with value.bold(), returns the same thing.

EDIT This is the HTML together with the JS that I m working on:

                <!DOCTYPE html>
            <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
            <head>
            <title>Test</title>

            <script>

            function myFunction(){
                var children = document.body.childNodes;
                for(var len = children.length, child=0; child<len; child++){
                 if (children[child].nodeType === 3){ // textnode
                    var highLight = new Array('abcd', 'edge', 'rss feeds');
                    var contents = children[child].nodeValue;
                    var output = contents; 
                    for(var i =0;i<highLight.length;i++){
                        output = delimiter(output, highLight[i]); 
                    }

                                children[child].nodeValue= output; 
                }
                }
            }

            function delimiter(input, value) {
                return unescape(input.replace(new RegExp('(\\b)(' + value + ')(\\b)','ig'), '$1<b>$2</b>$3'));
            }
            </script>



            </head>
            <body>
            <img src="http://some.web.site/image.jpg" title="knorex"/>

            These words are highlighted: abcd, edge, rss feeds while these words are not: knewedge, abcdefgh, rss feedssss

            <input type ="button" value="Button" onclick = "myFunction()">
            </body>
            </html>

I'm basically getting the result of the delimiter function and changing the nodeValue of a child node.

Is it possible there is something wrong with the way I'm taking back what the function is returning to me?

This is what I do:

children[child].nodeValue = output;

Upvotes: 1

Views: 1638

Answers (1)

Jukka K. Korpela
Jukka K. Korpela

Reputation: 201866

You need to have the markup processed as HTML, instead of being just set to replace existing content in a text node. For this, replace the statement

children[child].nodeValue= output; 

by the following:

var newNode = document.createElement('span');
newNode.innerHTML = output;
document.body.replaceChild(newNode, children[child]); 

Upvotes: 5

Related Questions