Tutorials using JS
Find number of character in paragraph
given a paragraph element in the document, count the number of characters in the paragraph using JavaScript
Solution
the text in the paragraph is a string, and to get the number of characters in a paragraph, we can get the length of the string – paragraph text
pText.length
where pText
is the string representing the text content inside the paragraph, and length
is the string property
the steps would be
- get the paragraph element
- get the text content inside the paragraph using
textContent
property of paragraph element - get the length of the text using
String.length
property
Program
in the following HTML code, we have a paragraph element with some text in it. when user clicks on the button, we display the number of characters in the paragraph to pre#output
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Tutorial</h1>
<h2>Count number of characters in paragraph</h2>
<button id="myBtn">Click me</button><br>
<p id="myPara">Hello World. This is a paragraph.</p>
<pre id="output"></pre>
<script>
document.getElementById("myBtn").addEventListener("click", function() {
//get paragraph element
const para = document.getElementById("myPara");
//get text in paragraph
const paraText = para.textContent;
//get number of characters in the para
const len = paraText.length;
document.getElementById("output").innerHTML = len;
});
</script>
</body>
</html>