π String Operation
1. Repeat a String a Specified Number of Timesβ
Design a function that repeats a string a specified number of times.
I. Using repeat() (ES6+)β
Since String now supports repeat(), you can use it directly.
const repeatedString = 'Pitt';
console.log(`Name Repeat : ${repeatedString.repeat(3)}`); // "Name Repeat : PittPittPitt"
Referenceβ
II. Using a Loopβ
If you don't use repeat(), you can also use a loop with parameter validation, constrained to positive integers.
function repeatString(str, num) {
// Check if not a positive integer
if (num < 0 || !Number.isInteger(num)) {
throw new Error('Please enter a positive integer');
}
let repeatedString = '';
for (let i = 0; i < num; i++) {
repeatedString += str;
}
return repeatedString;
}
2. Extract File Name or Extension from a Stringβ
Design a getFileExtension() that extracts the file extension from a parameter. If there is no extension, return the file name.
const fileName = 'video.mp4';
const fileNameWithoutExtension = 'file';
const fileNameWithoutExtension2 = 'example.flv';
const fileNameWithoutExtension3 = 'movie.mov';
const fileNameWithoutExtension4 = '.gitignore';
I. Using split to Get the File Extensionβ
const getFileExtension = (fileName) => {
const fileNameSplit = fileName.split('.');
return fileNameSplit[fileNameSplit.length - 1];
};
console.log(getFileExtension(fileName)); // "mp4"
console.log(getFileExtension(fileNameWithoutExtension)); // "file"
console.log(getFileExtension(fileNameWithoutExtension2)); // "flv"
console.log(getFileExtension(fileNameWithoutExtension3)); // "mov"
console.log(getFileExtension(fileNameWithoutExtension4)); // ""
3. Find the Longest String in an Arrayβ
I. Using the sort() Methodβ
const stringArray = ['apple', 'banana', 'orange', 'kiwi', 'strawberry'];
const longestString = (stringArray) => {
return stringArray.sort((a, b) => b.length - a.length)[0];
};
console.log(longestString(stringArray)); // "strawberry"
II. Using the reduce() Methodβ
const stringArray = ['apple', 'banana', 'orange', 'kiwi', 'strawberry'];
const longestString = (stringArray) => {
return stringArray.reduce(
(acc, cur) => (acc.length > cur.length ? acc : cur),
''
);
};
console.log(longestString(stringArray)); // "strawberry"
4. Convert a String to camelCaseβ
Design a function that converts a string to camelCase.
I. Using the replace() Methodβ
const camelCase = (str) => {
return str.replace(/-([a-z])/g, (match, char) => char.toUpperCase());
};
console.log(camelCase('hello-world')); // "helloWorld"
II. Using the split() Methodβ
const camelCase = (str) => {
return str
.split('-')
.map((word, index) =>
index === 0 ? word : word.charAt(0).toUpperCase() + word.slice(1)
)
.join('');
};
console.log(camelCase('hello-world')); // "helloWorld"
5. Count Duplicate String Occurrences in an Arrayβ
I. Using the Map() Methodβ
const stringArray = [
'apple',
'banana',
'orange',
'kiwi',
'strawberry',
'apple',
];
const countDuplicateString = (stringArray) => {
const map = new Map();
stringArray.forEach((item) => {
map.set(item, (map.get(item) || 0) + 1);
});
return Object.fromEntries(map);
};
console.log(countDuplicateString(stringArray)); // { apple: 2, banana: 1, orange: 1, kiwi: 1, strawberry: 1 }
II. Using the reduce() Methodβ
const stringArray = [
'apple',
'banana',
'orange',
'kiwi',
'strawberry',
'apple',
];
const countDuplicateString = (stringArray) => {
return stringArray.reduce((acc, cur) => {
acc[cur] = (acc[cur] || 0) + 1;
return acc;
}, {});
};
console.log(countDuplicateString(stringArray)); // { apple: 2, banana: 1, orange: 1, kiwi: 1, strawberry: 1 }
III. Using Object.groupBy() (ES2023+)β
const stringArray = ['apple', 'banana', 'orange', 'kiwi', 'strawberry'];
const countDuplicateString = (stringArray) => {
return Object.groupBy(stringArray);
};
console.log(countDuplicateString(stringArray)); // { apple: 2, banana: 1, orange: 1, kiwi: 1, strawberry: 1 }
6. Extract and Deduplicate File Extensions from an Array of Stringsβ
I. Using the split() Methodβ
const files = [
'document.docx',
'image.jpg',
'script.js',
'style.css',
'data.json',
'image.png',
'new-image.png',
];
const getFileExtension = (files) => {
return files
.map((file) => file.split('.').pop())
.filter((file, index, self) => self.indexOf(file) === index);
};
console.log(getFileExtension(files)); // ["docx", "jpg", "js", "css", "json", "png"]