Javascript count symbols in string

How to Count Words and Characters in JavaScript

Most if not all developers have used some sort of character counter online to validate SEO, or to just see how many characters a string has. You can do this on your own website or internal tooling. It is simple JavaScript and can have a wide variety of uses throughout your career as a JavaScript developer. In this tutorial, we’ll be exploring how to count words and characters in JavaScript. We’ll be using the String constructor and the length property to get the word and character count for a string.

View This On YouTube

File Structure

index.html /sass style.scss /js Count.js /css (generated by Sass) style.css style.min.css 

Our HTML

  lang="en">  charset="UTF-8">  http-equiv="X-UA-Compatible" content="IE=edge">  name="viewport" content="width=device-width, initial-scale=1.0"> Character and Word Counter  rel="stylesheet" href="/css/style.min.css">   class="main"> Count Your Words and Characters  class="card"> Words  class="word-count">0   class="card"> Characters  class="character-count">0   class="count__textarea">This is sample text that should be counted on load. You've written  class="word-count">0 words and  class="character-count">0 characters.  src="/js/Count.js">   

The basic HTML is simple and has a textarea and different spans (2 displayed as cards, and 2 inline texts) to show the counts.

Our Count JS Class

class Count  constructor()  this.textArea = document.querySelector(".count__textarea") this.wordCount = document.querySelectorAll(".word-count") this.charCount = document.querySelectorAll(".character-count") /* bind(this) is used to make sure that the this keyword inside the updateCount method refers to the Count class */ window.addEventListener("load", this.updateCount.bind(this)) this.textArea.addEventListener("input", this.updateCount.bind(this)) > /** * trim() removes whitespace from both sides of a string * if the value is empty, return 0 * split() splits a string into an array of substrings, and returns the new array * @returns the number of words in the textarea */ countWords()  const value = this.textArea.value.trim() if(!value) return 0 return value.split(/\s+/).length > /** * length returns the length of a string * @returns the number of characters in the textarea */ countChars()  return this.textArea.value.length > /** * update the word and character count * forEach() calls a function once for each element in an array, in order * toString() converts a number to a string * @returns */ updateCount()  const numWords = this.countWords() const numChars = this.countChars() this.wordCount.forEach((wordCount) =>  wordCount.textContent = numWords.toString(10) >) this.charCount.forEach((charCount) =>  charCount.textContent = numChars.toString(10) >) > > new Count() // create a new instance of the Count class 

This is a really easy-to-use and simple class that gets the spans and textarea. Once it has those it either listens on page load or when the textarea input is changed. Once one of those events happens, it simply counts the words and characters and then displays the count in the spans we created in the HTML.

Sample Styles

I created a sample style in Sass. You don’t have to use it for your project, but it basically displays the cards and makes the inline text spans bold. You can copy the following to make it look just like my tutorial.

@import url('https://fonts.googleapis.com/css2?family=Open+Sans&display=swap'); $font-family: 'Open Sans', sans-serif; $font-size:16px; $primary-color: #38a4ef; body  font-size: $font-size; font-family: $font-family; width:100%; min-height:100vh; background-color:$primary-color; padding:0; margin:0; color:#fff; overflow:hidden; .main  width:60%; text-align:center; margin:10% auto; h1,h2  margin:0; padding:0; > .card  background-color:#fff; padding:3rem; border-radius: 5px; width:200px; display:inline-block; margin:1rem; color:#333; box-shadow: 15px 15px 0px 0px rgba(0,0,0,.2); span  font-size: 2rem; display:block; > > textarea  display:block; width:calc(100% - 2rem); height:200px; border:0; margin:1rem 0; padding:1rem; font-size: $font-size; border-radius: 5px; &:focus  outline:none; > > .word-count, .character-count  font-weight: bold; > > > 

Conclusion

There you go. With a few lines of code, you can create your own internal character and word counters using vanilla JS. I hope this helps. Let me know if you have any questions. Read more articles on DevDrawer

Источник

How to Count Characters in a Javascript String

The main idea is to count all the occurring characters in a string. If you have a string like aba , then the result should be .

What if the string is empty? Then the result should be an empty object literal, <> .

The solution in Javascript#

function count (string) < var count = <>; string.split('').forEach(function(s) < count[s] ? count[s]++ : count[s] = 1; >); return count; > 
const count = string => [. string].reduce((pre, val) => (pre[val] = -~pre[val], pre), <>); 

Test cases to validate our solution#

const chai = require("chai"); const assert = chai.assert; chai.config.truncateThreshold=0; describe("Count characters", function() < function objectEqual( x, y ) < if ( x === y ) return true; // if both x and y are null or undefined and exactly the same if ( ! ( x instanceof Object ) || ! ( y instanceof Object ) ) return false; // if they are not strictly equal, they both need to be Objects if ( x.constructor !== y.constructor ) return false; // they must have the exact same prototype chain, the closest we can do is // test there constructor. for ( let p in x ) < if ( ! x.hasOwnProperty( p ) ) continue; // other properties were tested using x.constructor === y.constructor if ( ! y.hasOwnProperty( p ) ) return false; // allows to compare x[ p ] and y[ p ] when set to undefined if ( x[ p ] === y[ p ] ) continue; // if they have the same strict value or identity then they are equal if ( typeof( x[ p ] ) !== "object" ) return false; // Numbers, Strings, Functions, Booleans must be strictly equal if ( ! Object.equals( x[ p ], y[ p ] ) ) return false; // Objects and Arrays must be tested recursively >for ( p in y ) < if ( y.hasOwnProperty( p ) && ! x.hasOwnProperty( p ) ) return false; // allows x[ p ] to be set to undefined >return true; > it ("should give empty object literal if string is empty", function()< //Test.assertEquals(true, objectEqual(count(""), <>)); assert.deepEqual(count(""), <>); >); it ("should get as a result two A characters", function () < //Test.assertEquals(true, objectEqual(count("aa"), < a: 2 >)); assert.deepEqual(count("aa"), < a: 2 >); >); it ("should get as a result of two a characters and two b characters", function () < //Test.assertEquals(true, objectEqual(count("aabb"), < a: 2, b: 2 >)); assert.deepEqual(count("aabb"), < a: 2, b: 2 >); >); it ("should get as a result of two a characters and two b characters, showing that the result order does not matter", function () < //Test.assertEquals(true, objectEqual(count("aabb"), < b: 2, a: 2 >)); assert.deepEqual(count("aabb"), < b: 2, a: 2 >); >); it("should check for adding varying number of characters, random number of a's and b's", function () < let word = "", a = 0, b = 0; for (; a < Math.random() * 100; a++) < word += "a"; >for (; b < Math.random() * 100; b++) < word += "b"; >//Test.assertEquals(true, objectEqual(count(word), < "a": a, "b": b >)); assert.deepEqual(count(word), < "a": a, "b": b >); >); >); 
  1. How to Increment/Decrement a value in React/NextJS
  2. Fixing: ImmutableService requires getRowNodeId() callback to be implemented, your row data need IDs
  3. Automatically Resize All Columns to Fit in Ag-Grid
  4. How to Get All Rows in Ag-Grid
  5. How to Download a CSV file using Javascript
  6. How to Format Numbers by Prepending 0 to single-digit numbers in Javascript
  7. Validate Email Address in Javascript
  8. Remove hash from window.location in Javascript
  9. How to use Google Analytics in AngularJS
  10. Comparing Java and Javascript

Источник

String: length

The length data property of a String value contains the length of the string in UTF-16 code units.

Try it

Value

Property attributes of String: length
Writable no
Enumerable no
Configurable no

Description

This property returns the number of code units in the string. JavaScript uses UTF-16 encoding, where each Unicode character may be encoded as one or two code units, so it’s possible for the value returned by length to not match the actual number of Unicode characters in the string. For common scripts like Latin, Cyrillic, wellknown CJK characters, etc., this should not be an issue, but if you are working with certain scripts, such as emojis, mathematical symbols, or obscure Chinese characters, you may need to account for the difference between code units and characters.

The language specification requires strings to have a maximum length of 2 53 — 1 elements, which is the upper limit for precise integers. However, a string with this length needs 16384TiB of storage, which cannot fit in any reasonable device’s memory, so implementations tend to lower the threshold, which allows the string’s length to be conveniently stored in a 32-bit integer.

  • In V8 (used by Chrome and Node), the maximum length is 2 29 — 24 (~1GiB). On 32-bit systems, the maximum length is 2 28 — 16 (~512MiB).
  • In Firefox, the maximum length is 2 30 — 2 (~2GiB). Before Firefox 65, the maximum length was 2 28 — 1 (~512MiB).
  • In Safari, the maximum length is 2 31 — 1 (~4GiB).

For an empty string, length is 0.

The static property String.length is unrelated to the length of strings. It’s the arity of the String function (loosely, the number of formal parameters it has), which is 1.

Since length counts code units instead of characters, if you want to get the number of characters, you can first split the string with its iterator, which iterates by characters:

function getCharacterLength(str)  // The string iterator that is used here iterates over characters, // not mere code units return [. str].length; > console.log(getCharacterLength("A\uD87E\uDC04Z")); // 3 

Examples

Basic usage

const x = "Mozilla"; const empty = ""; console.log(`$x> is $x.length> code units long`); // Mozilla is 7 code units long console.log(`The empty string has a length of $empty.length>`); // The empty string has a length of 0 

Strings with length not equal to the number of characters

const emoji = "😄"; console.log(emoji.length); // 2 console.log([. emoji].length); // 1 const adlam = "𞤲𞥋𞤣𞤫"; console.log(adlam.length); // 8 console.log([. adlam].length); // 4 const formula = "∀𝑥∈ℝ,𝑥²≥0"; console.log(formula.length); // 11 console.log([. formula].length); // 9 

Assigning to length

Because string is a primitive, attempting to assign a value to a string’s length property has no observable effect, and will throw in strict mode.

const myString = "bluebells"; myString.length = 4; console.log(myString); // "bluebells" console.log(myString.length); // 9 

Specifications

Browser compatibility

BCD tables only load in the browser

See also

Found a content problem with this page?

This page was last modified on May 31, 2023 by MDN contributors.

Your blueprint for a better internet.

MDN

Support

Our communities

Developers

Visit Mozilla Corporation’s not-for-profit parent, the Mozilla Foundation.
Portions of this content are ©1998– 2023 by individual mozilla.org contributors. Content available under a Creative Commons license.

Источник

Читайте также:  Re match python flags
Оцените статью