为字符串创建动态段落

时间:2014-02-19 10:12:53

标签: javascript jquery string substring

使用响应创建动态<p>元素时出现以下问题!回复是纯文本。我需要确定字符串是否包含换行符或段落分隔。

示例字符串

All rates are inclusive of the applicable Service charge, VAT, NBT & TDL currently at the prevailing 10%, 12%, 2% & 1% respectively. In the event of a change in the Service charge, VAT, NBT & TDL or the introduction of additional taxes, the Contract Rates will be adjusted accordingly.

 All rates are inclusive of the applicable Service charge, VAT, NBT & TDL currently at the prevailing 10%, 12%, 2% & 1% respectively. In the event of a change in the Service charge, VAT, NBT & TDL or the introduction of additional taxes, the Contract Rates will be adjusted accordingly.

 All rates are inclusive of the applicable Service charge, VAT, NBT & TDL currently at the prevailing 10%, 12%, 2% & 1% respectively. In the event of a change in the Service charge, VAT, NBT & TDL or the introduction of additional taxes, the Contract Rates will be adjusted accordingly.

这个字符串是三个段落组合在一起!如何识别每个单独的段落,以使用javascript为每个段落创建单独的<p>标记。

3 个答案:

答案 0 :(得分:2)

你应该发布一些代码,但试试这个

var paragraphed = "<p>" + originalString.split("\n").join("</p><p>") + "</p>";

答案 1 :(得分:0)

试试这个:

  var responsestr="<your response text here>";  /*assuming that variable responsestr holds the response*/
  var str=encodeURIComponent(responsestr);
  var pArray=str.split("%0D%0A");
  var result=[];
  for(var i=0;i<pArray.length;i++){
    result.push("<p>"+decodeURIComponent(pArray[i])+"</p>\r\n");
  }
  var finalstr=result.join("");

答案 2 :(得分:0)

如下:

var s = "your string";
var paragraphs = s.split("\n")
      .filter(function (item) { return item !== ""; })
      .map(function (item) { return "<p>" + item + "</p>"; });
相关问题