Javascript String-Based Questions: Functions Uses
This article illustrates the implementation of various JavaScript functions and explores scenarios in which they can be effectively used.
1. Reverse a String:
function reverseString(str) {
return str.split('').reverse().join('');
}
console.log(reverseString('hello')); // Output: 'olleh'2. Palindrome Check:
function isPalindrome(str) {
const reversed = str.split('').reverse().join('');
return str === reversed;
}
console.log(isPalindrome('level')); // Output: true3. Count Vowels:
function countVowels(str) {
const vowels = str.match(/[aeiou]/gi);
return vowels ? vowels.length : 0;
}
console.log(countVowels('hello')); // Output: 2str: This is the string that you want to search for matches within./.../: This denotes the start and end of a regular expression literal in JavaScript.[aeiou]: This is a character class that matches any one character that is either 'a', 'e', 'i', 'o', or 'u'. In regular expressions, square brackets are used to define a character class, and any character inside the brackets can be a valid match.gi: These are flags that modify how the regular expression is applied:
g(global): This flag indicates that the search for matches should be global, meaning it will find all matches in the input string, not just the first one.i(case-insensitive): This flag indicates that the search for matches should be case-insensitive, so it will match both uppercase and lowercase letters.
4. Anagram Check:
function areAnagrams(str1, str2) {
return str1.split('').sort().join('') === str2.split('').sort().join('');
}
console.log(areAnagrams('listen', 'silent')); // Output: true5. Remove Duplicates:
function removeDuplicates(str) {
return str
.split('')
.filter((char, index, self) => self.indexOf(char) === index)
.join('');
}
console.log(removeDuplicates('hello')); // Output: 'helo'6. Capitalize Words:
function capitalizeWords(str) {
return str.split(' ').map(word => word.charAt(0).toUpperCase() + word.slice(1)).join(' ');
}
console.log(capitalizeWords('hello world')); // Output: 'Hello World'7. String Compression:
function compressString(str) {
let compressed = '';
let count = 1;
for (let i = 0; i < str.length; i++) {
if (str[i] === str[i + 1]) {
count++;
} else {
compressed += str[i] + count;
count = 1;
}
}
return compressed.length < str.length ? compressed : str;
}
console.log(compressString('aabcccccaaa')); // Output: 'a2b1c5a3'8. Rotate String:
function rotateString(str, n) {
const index = n % str.length;
return str.slice(index) + str.slice(0, index);
}
console.log(rotateString('abcdef', 3)); // Output: 'defabc'9. Longest Substring Without Repeating Characters:
function longestSubstringWithoutRepeating(str) {
let longest = '';
let current = '';
for (let char of str) {
if (current.includes(char)) {
current = current.slice(current.indexOf(char) + 1);
}
current += char;
if (current.length > longest.length) {
longest = current;
}
}
return longest;
}
console.log(longestSubstringWithoutRepeating('abcabcbb')); // Output: 'abc'10. String to Integer (atoi):
function atoi(str) {
const num = parseInt(str);
if (isNaN(num)) {
return 0;
}
return Math.max(Math.min(num, 2**31 - 1), -(2**31));
}
console.log(atoi('42')); // Output: 42parseInt(str): This part converts the input stringstrto an integer. TheparseIntfunction attempts to parse a string and returns an integer. If the string does not start with a valid integer, it returnsNaN(Not a Number).isNaN(num): This condition checks if the result ofparseInt(str)isNaN. If it is, it means that the input string does not represent a valid integer. In this case, the function returns0.Math.min(num, 2**31 - 1): This part ensures that the parsed integer is not greater than2^31 - 1(the maximum value for a 32-bit signed integer in JavaScript). If the parsed integer is greater, it is set to2^31 - 1.Math.max(..., -(2**31)): This part ensures that the parsed integer is not less than-2^31(the minimum value for a 32-bit signed integer in JavaScript). If the parsed integer is less, it is set to-2^31.
Get Amit Dhiman’s stories in your inbox
Join Medium for free to get updates from this writer.
11. First Unique Character in a String:
function firstUniqueChar(str) {
const charCount = {};
for (let char of str) {
charCount[char] = (charCount[char] || 0) + 1;
}
for (let i = 0; i < str.length; i++) {
if (charCount[str[i]] === 1) {
return i;
}
}
return -1;
}
console.log(firstUniqueChar('leetcode')); // Output: 012. Group Anagrams:
function groupAnagrams(words) {
const anagramGroups = {};
for (let word of words) {
const sortedWord = word.split('').sort().join('');
if (!anagramGroups[sortedWord]) {
anagramGroups[sortedWord] = [];
}
anagramGroups[sortedWord].push(word);
}
return Object.values(anagramGroups);
}
console.log(groupAnagrams(['eat', 'tea', 'tan', 'ate', 'nat', 'bat']));
// Output: [['eat', 'tea', 'ate'], ['tan', 'nat'], ['bat']]13. String to Camel Case:
function toCamelCase(str) {
return str.replace(/[-_](.)/g, (_, char) => char.toUpperCase());
}
console.log(toCamelCase('my-variable-name')); // Output: 'myVariableName'14. String to Title Case:
function toTitleCase(str) {
return str.replace(/\b\w/g, char => char.toUpperCase());
}
console.log(toTitleCase('hello world')); // Output: 'Hello World'15. Valid Parentheses:
function isValidParentheses(str) {
const stack = [];
const pairs = { ')': '(', '}': '{', ']': '[' };
for (let char of str) {
if (char in pairs) {
if (stack.pop() !== pairs[char]) {
return false;
}
} else {
stack.push(char);
}
}
return stack.length === 0;
}
console.log(isValidParentheses('()[]{}')); // Output: true16. String Rotation Check:
function isRotation(str1, str2) {
if (str1.length !== str2.length) {
return false;
}
return (str1 + str1).includes(str2);
}
console.log(isRotation('waterbottle', 'erbottlewat')); // Output: true17. Minimum Window Substring:
function minWindowSubstring(s, t) {
let start = 0;
let minLen = Infinity;
let minWindow = '';
let missingChars = t.length;
const charCount = {};
for (let char of t) {
charCount[char] = (charCount[char] || 0) + 1;
}
for (let end = 0; end < s.length; end++) {
if (charCount[s[end]] > 0) {
missingChars--;
}
charCount[s[end]]--;
while (missingChars === 0) {
if (end - start < minLen) {
minLen = end - start;
minWindow = s.slice(start, end + 1);
}
charCount[s[start]]++;
if (charCount[s[start]] > 0) {
missingChars++;
}
start++;
}
}
return minWindow;
}
console.log(minWindowSubstring('ADOBECODEBANC', 'ABC')); // Output: 'BANC'18. Count and Say:
function countAndSay(n) {
if (n === 1) return '1';
const prev = countAndSay(n - 1);
let result = '';
let count = 1;
for (let i = 0; i < prev.length; i++) {
if (prev[i] === prev[i + 1]) {
count++;
} else {
result += count + prev[i];
count = 1;
}
}
return result;
}
console.log(countAndSay(4)); // Output: '1211'19. Longest Common Prefix:
function longestCommonPrefix(strs) {
if (strs.length === 0) return '';
let prefix = strs[0];
for (let i = 1; i < strs.length; i++) {
let j = 0;
while (j < prefix.length && j < strs[i].length && prefix[j] === strs[i][j]) {
j++;
}
prefix = prefix.slice(0, j);
}
return prefix;
}
console.log(longestCommonPrefix(['flower', 'flow', 'flight'])); // Output: 'fl'20. ZigZag Conversion:
function convertZigZag(s, numRows) {
if (numRows === 1) return s;
const rows = Array.from({ length: Math.min(numRows, s.length) }, () => '');
let currentRow = 0;
let goingDown = false;
for (let char of s) {
rows[currentRow] += char;
if (currentRow === 0 || currentRow === numRows - 1) {
goingDown = !goingDown;
}
currentRow += goingDown ? 1 : -1;
}
return rows.join('');
}
console.log(convertZigZag('PAYPALISHIRING', 3)); // Output: 'PAHNAPLSIIGYIR'21. Unique Values
const nestedArray = [1, [2, [3, [4]]]];
const nestedArray1 = [2, [4, [6, [8]]]];
// Merge arrays and flatten to a single depth
const mergedArray = [...nestedArray, ...nestedArray1].flat(Infinity);
// Use a Set to remove duplicates
const uniqueArray = Array.from(new Set(mergedArray));
console.log(uniqueArray);These examples cover a range of string manipulation techniques and can serve as good practice.
Stackademic
Thank you for reading until the end. Before you go:
- Please consider clapping and following the writer! 👏
- Follow us on Twitter(X), LinkedIn, and YouTube.
- Visit Stackademic.com to find out more about how we are democratizing free programming education around the world.








