计算包括HTML标签的字符数,包括换行符。

huangapple go评论50阅读模式
英文:

Count Characters Including the Break Line of an HTML TAG

问题

我有一个正则表达式来移除HTML标签以计算我的字符数。目前它正常工作。

<string_variable>.replaceAll("<(.|\n)*?>","").replaceAll("&nbsp;"," ").replaceAll("&amp;","&");

alert <string_variavle>.length()

但我需要添加<br/>(换行符)以计算我的字符数。

<div>ABC<br /><br />DEC</div>

例如,上面的ABC和DEC有6个字符,有2个换行符,应该是9个字符。目前它只计算为6个字符。

搜索类似问题。
调整我的代码。

英文:

I have a regex to remove the html tags to count my characters. Which is working fine.

&lt;string_variable&gt;.replaceAll(&quot;&lt;(.|\n)*?&gt;&quot;,&quot;&quot;).replaceAll(&quot;&amp;nbsp;&quot;,&quot; &quot;).replaceAll(&quot;&amp;amp;&quot;,&quot;&amp;&quot;);

alert &lt;string_variavle&gt;.length()

But I need to add the <br/> (New Line) to count my characters.

> <div>ABC<br /><br />DEC</div>

For example above ABC and DEC are 6 characters with 2 break lines it should be 9. As of now it is just counting with 6 characters.

Search for similar issue.
Tweaking my code

答案1

得分: 0

你可以系统地将所有的\n替换为不同的字符,然后使用长度:

const temp = myVar.replaceAll("\n", "a")
console.log(temp.length)
英文:

You can systematically replace all of your \n to a different char and then use the length:

const temp = myVar.replaceAll(&quot;\n&quot;, &quot;a&quot;)
console.log(temp.length)

答案2

得分: 0

let str = `
    <div>
      abc
    </div>
    <div>
      abc
    </div>`

console.log(countNewlines(str))

function countNewlines(input) {
  let count = 0;
  for (let i = 0; i < input.length; i++) {
    if (input[i] === '\n') {
      count++;
    }
  }
  return count;
}
英文:

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

let str = `
    &lt;div&gt;
      abc
    &lt;/div&gt;
    &lt;div&gt;
      abc
    &lt;/div&gt;`

console.log(countNewlines(str))

function countNewlines(input) {
  let count = 0;
  for (let i = 0; i &lt; input.length; i++) {
    if (input[i] === &#39;\n&#39;) {
      count++;
    }
  }
  return count;
}

<!-- end snippet -->

huangapple
  • 本文由 发表于 2023年6月13日 13:28:55
  • 转载请务必保留本文链接:https://go.coder-hub.com/76461910.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定