@devdynamo/string-utils
v1.0.1
Published
A collection of useful string manipulation functions
Maintainers
Readme
String Manipulation Utility Functions
This repository contains various JavaScript functions for manipulating strings in creative and useful ways.
Functions Included
1. Title Case a Sentence
Each word in the sentence starts with a capital letter.
function titleCase(sentence) {
return sentence
.split(' ')
.map(word => word.charAt(0).toUpperCase() + word.slice(1).toLowerCase())
.join(' ');
}Example:
titleCase("hello world from javascript");
// Output: "Hello World From Javascript"2. Alternate Case (Weird Caps)
Every alternate character is uppercase.
function alternateCase(str) {
return str.split('')
.map((char, index) => index % 2 === 0 ? char.toUpperCase() : char.toLowerCase())
.join('');
}Example:
alternateCase("javascript is fun");
// Output: "JaVaScRiPt iS FuN"3. Shuffle Characters in a String
Randomly rearranges the characters of the string.
function shuffleString(str) {
return str.split('')
.sort(() => Math.random() - 0.5)
.join('');
}Example:
shuffleString("hello");
// Output: Random variations like "ollhe", "hlelo"4. Remove Vowels from a String
Removes all vowels (a, e, i, o, u) from the string.
function removeVowels(str) {
return str.replace(/[aeiouAEIOU]/g, '');
}Example:
removeVowels("beautiful world");
// Output: "btfl wrld"5. Find the Most Frequent Character
Finds the character that appears most in a string.
function mostFrequentChar(str) {
let charMap = {};
let maxChar = '';
let maxCount = 0;
for (let char of str) {
charMap[char] = (charMap[char] || 0) + 1;
if (charMap[char] > maxCount) {
maxCount = charMap[char];
maxChar = char;
}
}
return maxChar;
}Example:
mostFrequentChar("success");
// Output: "s"6. Encode String with ASCII Codes
Converts each character to its ASCII equivalent.
function encodeASCII(str) {
return str.split('').map(char => char.charCodeAt(0)).join('-');
}Example:
encodeASCII("hello");
// Output: "104-101-108-108-111"7. Expand Abbreviations (Dynamic Version)
Expands common abbreviations in a string with an option for custom mappings.
function expandAbbreviations(str, customMap = {}) {
const defaultMap = {
"brb": "be right back",
"gtg": "got to go",
"idk": "I don't know",
"imo": "in my opinion",
"ttyl": "talk to you later"
};
const abbreviationMap = { ...defaultMap, ...customMap };
return str.split(' ').map(word => abbreviationMap[word.toLowerCase()] || word).join(' ');
}Example:
expandAbbreviations("brb I will ttyl");
// Output: "be right back I will talk to you later"
const customMap = {
"asap": "as soon as possible",
"np": "no problem",
"fyi": "for your information"
};
expandAbbreviations("fyi brb asap", customMap);
// Output: "for your information be right back as soon as possible"How to Use
- Copy the function you need.
- Paste it into your JavaScript project.
- Call the function with appropriate parameters.
