Reputation: 1315
I can have string parameters like these to my function.
"Hello World <a>This is Link</a>"
"<span> Hello World </span><a>This is Link</a>"
"Hello <br> World <a>This is Link</a>"
I want to get character count of the text by not including dom elements tags.(like <a> or <br>
)I only want character count.
Any suggestion?
Upvotes: 2
Views: 1489
Reputation: 68933
Use /<[^>]*>/g
to find all the tags. Try the following way (space not counted):
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));
OR: If you want the spaces to be counted:
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));
Upvotes: 1
Reputation: 586
Put the string into a node and get the length of textConent
attribute.
(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>'));
Upvotes: 1
Reputation: 636
Regexp based solution:
function removeHtmlTags (htmlString) {
return htmlString
.replace(/(<{1}[^>]*>)?/g, "")
.replace(/(<\/{1}[^>]*>)?/g, "");
}
Upvotes: 0
Reputation: 3148
Try using regex: /(<\/?\w+>)/ig
<
\/?
\w+
>
ig
for global and case insensitiveYou will get all the opening and closing tags. Just make them empty using replace and count the length of the rest of the string.
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));
Upvotes: 0
Reputation: 2585
this is it
mstring = "Hello <br> World <a>This is Link</a>";
cleanText = mstring.replace(/<\/?[^>]+(>|$)/g, "");
console.log(cleanText.length);
Upvotes: 2