英文:
Count Characters Including the Break Line of an HTML TAG
问题
我有一个正则表达式来移除HTML标签以计算我的字符数。目前它正常工作。
<string_variable>.replaceAll("<(.|\n)*?>","").replaceAll(" "," ").replaceAll("&","&");
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.
<string_variable>.replaceAll("<(.|\n)*?>","").replaceAll("&nbsp;"," ").replaceAll("&amp;","&");
alert <string_variavle>.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("\n", "a")
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 = `
<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;
}
<!-- end snippet -->
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论