Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Encrypting censored words using JavaScript
This tutorial demonstrates how to encrypt or mask censored words in JavaScript by applying specific transformation rules to convert regular text into a masked format.
Problem
We need to write a JavaScript function that takes in a string and converts it according to the following rules:
- All words should be in uppercase
- Every word should end with '!!!!'
- Any letter 'a' or 'A' should become '@'
- Any other vowel (E, I, O, U) should become '*'
Solution
Here's the implementation of the word masking function:
const str = 'ban censored words';
const maskWords = (str = '') => {
let arr = str.split(' ');
const res = [];
for (let i = 0; i < arr.length; ++i) {
let s = (arr[i].toUpperCase() + '!!!!').split('');
for (let j = 0; j < s.length; ++j) {
if (s[j] == 'A')
s[j] = '@';
if (s[j] == 'E' || s[j] == 'I' || s[j] == 'O' || s[j] == 'U')
s[j] = '*';
}
res.push(s.join(''));
}
return res.join(' ');
};
console.log(maskWords(str));
B@N!!!! C*NS*R*D!!!! W*RDS!!!!
How It Works
The function processes the input string through these steps:
- Split the string: Divides the input into individual words using space as delimiter
- Process each word: Converts to uppercase and appends '!!!!'
- Character transformation: Iterates through each character and applies vowel masking rules
- Reconstruct: Joins characters back into words and words back into the final string
Alternative Implementation
Here's a more concise version using array methods and regular expressions:
const maskWordsAdvanced = (str = '') => {
return str.split(' ')
.map(word => word.toUpperCase() + '!!!!')
.map(word => word.replace(/A/g, '@').replace(/[EIOU]/g, '*'))
.join(' ');
};
const testStr = 'hello world amazing';
console.log(maskWordsAdvanced(testStr));
H*LL*!!!! W*RLD!!!! @M@Z*NG!!!!
Key Points
- The function handles empty strings with a default parameter
- Character replacement is case-sensitive after converting to uppercase
- The '!!!!' suffix is added before vowel replacement to avoid masking exclamation marks
- The algorithm preserves word boundaries and spacing
Conclusion
This word masking technique provides a simple way to obfuscate text by replacing vowels with symbols. It's useful for censoring content while maintaining readability and can be customized with different replacement rules.
Advertisements
