如何在使用jquery / javascript时打破行尾的?

时间:2019-02-12 11:27:45

标签: javascript jquery html

我有一个表,如下所示:

$(document).ready(function() {
var enteredText = document.getElementById("textArea").value;

	var numberOfLineBreaks = (enteredText.match(/\n/g)||[]).length;
	var characterCount = enteredText.length + numberOfLineBreaks;

	alert('Number of breaks:  ' + numberOfLineBreaks);
      
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<head>
	<title></title>
</head>
<body>
<table class="tapshil" id="" border="2px" width="100%">
   <thead>
      <tr>
         <th> <font face="preeti">l;=g+=</font></th>
         <th><font face="preeti"> k|=b=g</font></th>
         <th><font face="preeti"> ldlt</font></th>
         <th><font face="preeti"> eG;f/ dx;'n tyf hl/jfgf</font> </th>
         <th><font face="preeti"> cGtMz'Ns</font></th>
         <th><font face="preeti"> d"=c=s/ </font></th>
         <th><font face="preeti"> hDdf dx;'n</font> </th>
         <th><font face="preeti"> hDdf  </font> </th>
      </tr>
   </thead>
   <tbody>
      <!-- put loop here -->
      <tr>
         <td>1</td>
         <td>11
            1212231
         </td>
         <td id="textArea">भैरवा भन्सार  2070-01-01 2072-01-01 बिराटनगर भन्सार  2070-01-01 2072-01-01
         </td>
         <td>3</td>
         <td>7</td>
         <td>11</td>
         <td>15</td>
         <td id="totalOfAll">36</td>
      </tr>
   </tbody>
</table>
</body>

</html>

在我的用户界面中,它显示为:

init(data:encoding:)

在我的表中有一个数据输入如:

 <td id="textArea">भैरवा भन्सार  2070-01-01 2072-01-01 बिराटनगर भन्सार  2070-01-01 2072-01-01
             </td>

我想在भैरवा भन्सार 2070-01-01 2072-01-01之后进行拆分,并将बिराटनगर भन्सार 2070-01-01 2072-01-01带到新行,但是它没有出现。在我的UI中,它是直线出现的。我如何将其分解为新的线?我希望输出如下:

 <td id="textArea">भैरवा भन्सार  2070-01-01 2072-01-01
                   बिराटनगर भन्सार  2070-01-01 2072-01-01
   </td>

1 个答案:

答案 0 :(得分:0)

我建议不要使用Javascript / JQuery格式化文本,而是在呈现文本时对其进行格式化。

根据您的示例,假设<td>标签中显示的文本具有固定格式(如下所示),则可以使用空格('')解析文本,并根据显示内容对其进行格式设置要求。

Fixed format: firstName lastName Date1 Date2 firstName lastName Date1 Date2 ...

解决方案:

<script>
    $(document).ready(function() {
        var enteredText = $("#textArea").html(); //Get the InnerHTML

        var NumOfOccurrences = (enteredText.match(/\s/g) || []).length; //All the occurrences of space (' ')
        var n = 3; //Initial occurrence
        while(n <= NumOfOccurrences) {
            enteredText = enteredText.replace(RegExp("^(?:.*? ){" + n + "}"), function(val){return val.replace(RegExp(' ' + "$"), "<br>")}); //Replace the occurrence
            n = n+ 2; //Increment by 2 to determine next occurrence
        }
        $("#textArea").html(enteredText); //Replace the InnerHTML
    });
</script>