手记

js简单实现文本某个字加粗

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
	</head>
	<body>
		<div>曾经沧海难为水,除去巫山不是云 取次花丛懒回顾,半缘修道半缘君</div>
	</body>
</html>
	//方法1
	function highLightCode0(node, keyworlds) {
		var patt = new RegExp((keyworlds), "g")
		//replace 传入函数 arguments[0] 是匹配到的内容            
		node.innerHTML = node.textContent.replace(patt, function() {
			return "<strong>" + arguments[0] + "</strong>"
		})
	}
//方法2
	function highLightCode1(node, keyworlds) {
		var text = node.textContent;
		node.textContent = null;
		var patt = new RegExp(keyworlds, "g") var match, pos = 0;
		while (match = patt.exec(text)) { //匹配词语的之前部分    
			node.appendChild(document.createTextNode(text.slice(pos, match.index))); //匹配词语      
			var strong = document.createElement("strong");
			strong.appendChild(document.createTextNode(match[0]));
			node.appendChild(strong);
			pos = patt.lastIndex;
		} //匹配词语的之后部分          
	node.appendChild(document.createTextNode(text.slice(pos)))}
new highLightCode(document.querySelector("div"), "半")
2人推荐
随时随地看视频
慕课网APP