Dom Elements的字符数

时间:2018-07-10 14:27:44

标签: javascript jquery

我可以在函数中使用类似这样的字符串参数。

"Hello World <a>This is Link</a>"
"<span> Hello World </span><a>This is Link</a>"
"Hello <br> World <a>This is Link</a>"

我想通过不包括dom元素标签来获得文本的字符数。(like <a> or <br>)我只想要字符数。

有什么建议吗?

5 个答案:

答案 0 :(得分:1)

就这样

mstring = "Hello <br> World <a>This is Link</a>";
cleanText = mstring.replace(/<\/?[^>]+(>|$)/g, "");
console.log(cleanText.length);

答案 1 :(得分:1)

将字符串放入节点并获得textConent属性的长度。

(function () {
    var node = document.createElement('pre');
    window.getCharCount = function (html) {
        node.innerHTML = html;
        return node.textContent.length;
        // return node.textContent.trim().length;   // if you want to ignore spaces at beginning and end
    };
}());

console.log(getCharCount('Hello World <a>This is Link</a>'));
console.log(getCharCount('<span> Hello World </span><a>This is Link</a>'));
console.log(getCharCount('Hello <br> World <a>This is Link</a>'));

答案 2 :(得分:0)

使用/<[^>]*>/g查找所有标签。请尝试以下方式(不计算空间):

var str1 = "Hello World <a>This is Link</a>";
var str2 = "<span> Hello World </span><a>This is Link</a>";
var str3 = "Hello <br> World <a>This is Link</a>";

function getCharLen(str){
  str = str.replace(/<[^>]*>/g, "").split('').filter(i=>i!=' ');
  return str.length;
}

console.log(getCharLen(str1));
console.log(getCharLen(str2));
console.log(getCharLen(str3));

或::如果要计算空格:

var str1 = "Hello World <a>This is Link</a>";
var str2 = "<span> Hello World </span><a>This is Link</a>";
var str3 = "Hello <br> World <a>This is Link</a>";

function getCharLen(str){
  str = str.replace(/<[^>]*>/g, "");
  return str.length;
}

console.log(getCharLen(str1));
console.log(getCharLen(str2));
console.log(getCharLen(str3));

答案 3 :(得分:0)

尝试使用正则表达式:/(<\/?\w+>)/ig

  • <开头
  • 结束标记\/?的可选斜杠
  • 任何文字字符\w+
  • >结尾
  • 修饰符ig用于全局且不区分大小写

您将获得所有的开始和结束标签。只需使用replace使它们为空,并计算其余字符串的长度即可。

function count(str) {
  var regex = /(<\/?\w+>)/ig;
  return str.replace(regex, '').length;
}


/* Test */

var a = "Hello World <a>This is Link</a>";
var b = "<span> Hello World </span><a>This is Link</a>";
var c = "Hello <br> World <a>This is Link</a>";

console.log(count(a));
console.log(count(b));
console.log(count(c));

答案 4 :(得分:0)

基于Regexp的解决方案:

function removeHtmlTags (htmlString) {
  return htmlString
    .replace(/(<{1}[^>]*>)?/g, "")
    .replace(/(<\/{1}[^>]*>)?/g, "");
}