html如何使文本变为粗体_使HTML文本变为粗体

I wrote this function which takes in a word as input and puts it in a 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 tag arround it.

Here is the function:

function delimiter(input, value) {

return input.replace(new RegExp('(\\b)(' + value + ')(\\b)','ig'), '$1$2$3');

}

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

The output is: This is a test message

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:

Test

function myFunction(){

var children = document.body.childNodes;

for(var len = children.length, child=0; 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

output = delimiter(output, highLight[i]);

}

children[child].nodeValue= output;

}

}

}

function delimiter(input, value) {

return unescape(input.replace(new RegExp('(\\b)(' + value + ')(\\b)','ig'), '$1$2$3'));

}

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

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;

解决方案

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]);

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值