
- Javascript Basics Tutorial
- Javascript - Home
- Javascript - Overview
- Javascript - Syntax
- Javascript - Enabling
- Javascript - Placement
- Javascript - Variables
- Javascript - Operators
- Javascript - If...Else
- Javascript - Switch Case
- Javascript - While Loop
- Javascript - For Loop
- Javascript - For...in
- Javascript - Loop Control
- Javascript - Functions
- Javascript - Events
- Javascript - Cookies
- Javascript - Page Redirect
- Javascript - Dialog Boxes
- Javascript - Void Keyword
- Javascript - Page Printing
- JavaScript Objects
- Javascript - Objects
- Javascript - Number
- Javascript - Boolean
- Javascript - Strings
- Javascript - Arrays
- Javascript - Date
- Javascript - Math
- Javascript - RegExp
- Javascript - HTML DOM
- JavaScript Advanced
- Javascript - Error Handling
- Javascript - Validations
- Javascript - Animation
- Javascript - Multimedia
- Javascript - Debugging
- Javascript - Image Map
- Javascript - Browsers
- JavaScript Useful Resources
- Javascript - Questions And Answers
- Javascript - Quick Guide
- Javascript - Functions
- Javascript - Resources
Compressing string in JavaScript
We are required to write a JavaScript function that takes in a string that might contain some continuous repeating characters.
The function should compress the string like this −
'wwwaabbbb' -> 'w3a2b4' 'kkkkj' -> 'k4j'
And if the length of the compressed string is greater than or equal to the original string we should return the original string.
For example −
'aab' can be compressed to 'a2b1' but it increases its length to 4 so our function should return 'aab'
Example
The code for this will be −
const str1 = 'wwwaabbbb'; const str2 = 'kkkkj'; const str3 = 'aab'; const compressString = (str = '') => { let res = ''; let count = 1; for(let i = 0; i < str.length; i++){ let cur = str[i]; let next = str[i + 1]; if(cur === next){ count++; }else{ res += cur + String(count); count = 1; }; } return res.length < str.length ? res : str; }; console.log(compressString(str1)); console.log(compressString(str2)); console.log(compressString(str3));
Output
And the output in the console will be −
3a2b4 k4j1 aab
- Related Articles
- Compressing a File in Golang
- Compressing and Decompressing files in C#
- Best Online Tools for Compressing Images
- Compressing and Decompressing files using GZIP Format in C#
- Hyphen string to camelCase string in JavaScript
- Repeat String in JavaScript?
- Similar string groups in JavaScript
- Magical String: Question in JavaScript
- Uncamelising a string in JavaScript
- Truncating a String in JavaScript
- String to binary in JavaScript
- Keeping only alphanumerals in a JavaScript string in JavaScript
- Interchanging a string to a binary string in JavaScript
- Finding mistakes in a string - JavaScript
- Avoid Unexpected string concatenation in JavaScript?

Advertisements