简单的解析font标签

利用font标签来给某些字符设定字号、颜色、和是否加粗。

var log = console.log;

var str = "abc<font color='#ffee00'>123</font>oooo<b>oo</b>ooooo<font color='#ff2300' size='26'>ppppppp<b>我擦</b>ppp<b>嗷嗷嗷</b>p</font>点点点";

function Data(str, color, size, isBold) {
	this.str 	= str;
	this.color 	= color || "#ffffff";
	this.size 	= size || 30;
	this.isBold = isBold || false;
}

// 解析font标签中的属性:size、color
function parseFont(html) {
	var size 	= undefined;
	var color 	= undefined;
	if(html[0] == '<' && html[1] == 'f') {
		for(var i = 0; i < html.length; i++) {
			if(html[i] == 's') {	// 目前需求只需要解析size和color所以只有判断字符是不是s就知道是不是检测到有size这个属性
				var j = i;
				while(html[j] != "'") {
					j++;
				}
				var start = j + 1;
				j = start;
				while(html[j] != "'") {
					j++;
				}
				var end = j;
				var num = html.substring(start, end);
				var size = parseInt(num);
			}
			if(html[i] == 'c') {
				var j = i;
				while(html[j] != "'") {
					j++;
				}
				var start = j + 1;
				j = start;
				while(html[j] != "'") {
					j++;
				}
				var end = j;
				var hex = html.substring(start, end);
				var color = hex;
			}
			if(html[i] == '>') {
				break;
			}
		}
	} 
	return {"color":color, "size":size};
}

function parse(html) {
	var chList 		= [];
	var dataList 	= [];
	var size 		= undefined;
	var color 		= undefined;
	var bold 		= undefined;
	log(html)
	for(var i = 0; i < html.length; i++) {
		if(html[i] == '<') {
			if(chList.length > 0) {
				var str = chList.join("");
				var data = new Data(str, color, size, bold);
				dataList.push(data);
				chList = [];
			}
			if(html[i + 1] == '/') {
				if(html[i + 2] == 'f') {
					size = undefined;
					color = undefined;
				} else if(html[i + 2] == 'b') {
					bold = undefined;
				}
				var j = i;
				while(html[j] != '>') {
					j++;
				}
				i = j;
			} else if(html[i + 1] == 'f') {
				var d = parseFont(html.substring(i, html.length));
				size = d["size"];
				color = d["color"];
			} else if(html[i + 1] == 'b') {
				bold = true;
			}
			var j = i;
			while(html[j] != '>') {
				j++;
			}
			i = j;
		} else {
			chList.push(html[i]);
		}
	}
	if(chList.length > 0) {
		var str = chList.join("");
		var data = new Data(str, color, size, bold);
		dataList.push(data);
		chList = [];
	}
	return dataList;
}

log(parse(str));


  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

shangdibaozi

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值