js实现文本分段
本菜鸟的第一篇博文,最近在学习js,可能有很多不严谨或者不正确的地方,欢迎指正
在.net开发中,有时候会从后台数据库拉来一大串文本,放到页面上显示。那么问题来了,大段的文本中需要分段,一般分段在后台都用转义字符\n来表示,但是我们现在要把文本放入到一个<div>当中,但是dom元素节点只有<textarea>可以识别转义字符。
我们可以通过javascript来实现这个功能,比方说我们要把这一段文字显示在网页上:
Aqeela Asifi,
who fled to Pakistan as a young woman,
has spent her life teaching other Afghan refugees.
它在后台作为一个string变量的值是这样:“Aqeela Asifi,\r\nwho fled to Pakistan as a young woman,\r\nhas spent her life teaching other Afghan refugees.”
通过后台c#的replace方法将转义字符替换成‘~’传到了前端页面上,具体操作这里不多说了,变成如下这样:
“Aqeela Asifi,~nwho fled to Pakistan as a young woman,~has spent her life teaching other Afghan refugees.”
现在可以用js来处理了,js处理的逻辑是根据文本中的‘~’字符来分割并将分割后的字符串前后加上<p></p>元素节点,这样就组装成html语言了,然后通过innerhtml属性添加到一个<div>中显示在页面上
完整的html代码:
<html>
<body>
<div id="content"></div>
</body>
<script src="Scripts/jquery-1.7.1.js"></script>
<script>
//输出的内容
var content = "Aqeela Asifi, ~ who fled to Pakistan as a young woman, has spent her life teaching other Afghan refugees. ~ Aqeela Asifi ~ For her efforts, Ms. Asifi, who is 49, has won the 2015 UNHCR Nansen Refugee award. She also gets $100,000 to help pay for her education projects."
//单独段落
para = ""
//添加<p>元素处理后的段落
inner = ""
for (a = 0; a < content.length;) {
if (content[a] != '~') {
para += content[a];//根据'~'字符来对内容分割
}
else {
inner += insertparagraph(para);//分割的单一段落内容放入到<p>元素中
para = "";//清空
}
a++;
}
inner += insertparagraph(para);//添加最后一段内容
document.getElementById("content").innerHTML = inner;
//放入到<p>元素中
function insertparagraph(text) {
var str = "<p>"
str += text;
str += "</p>"
return str;
}
</script>
</html>