Word & Character counter in JavaScript | Regex

Word & Character counter in JavaScript | Regex

preview

In this project we will see how to build a Word/Character counter app using Html, Css and javaScript with Regular Expressions.

Word/Character counter is a web application or a tool which is helpful to find the total count of characters and words given as an input. To achieve this functionality, we use length property and Regex in to find out total count.

Please follow the below code and get started 🚀.

Html code
<div class="container">
  <h1 class="title">Word and Character<br/> Counter</h1>
  <textarea id="textarea" cols="30" rows="10" placeholder="Start typing here..."></textarea>
  <div class="result">
    <div class="char-count-result">
      <p>Total Chars</p>
      <span id="chars">0</span>
    </div>
    <div class="word-count-result">
      <p>Total Words</p>
      <span id="words">0</span>
    </div>
  </div>
</div>

Css code
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

body {
  min-height: 100vh;
  background: #f1f2f3;
  font-family: monospace, sans-serif;
  display: flex;
}

.container {
  margin: auto;
  width: 500px;
  max-width: 100%;
  padding: 1rem;
  background: #fff;
  text-align: center;
  box-shadow: 0 6px 25px rgba(0,0,0,.1);
  border-radius: 0.5rem;
}

#textarea {
  margin: 2rem 0;
  width: 100%;
  height: 240px;
  border: 1px solid #ccc;
  border-radius: .5rem;
  padding: .5rem;
}

.result {
  display: flex;
  align-items: center;
  gap: 1rem;
}

.result div {
  flex: 1;
  background: #347cfe;
  border-radius: .25rem;
  padding: .5rem;
  color: #fff;
}

span {
  font-size: 1.5rem;
  font-weight: 600
}

JavaScript code
// selectors
const textEle = document.getElementById("textarea")
const charEle = document.getElementById("chars")
const wordEle = document.getElementById("words")

textEle.addEventListener("keyup", e => {
  // get user input and trim   
  let input = e.target.value.trim()
  
  // get words using regex   
  let wordCnt = input.match(/[\w]+/g);
  
  // dispaly char and word counts
  charEle.innerText = input.length
  wordEle.innerText = wordCnt ? wordCnt.length : 0
})

That is all! Thank you for visiting my blog:)

Code By: Altaf Alam Shaikh
Post a Comment (0)
Previous Post Next Post