Exercise
You can check if a string contains only alphabetic characters in JavaScript using regular expressions.
var str = 'HelloWorld';
var isAlphabetic = /^[a-zA-Z]+$/.test(str); // isAlphabetic will be true
You can check if a string contains only numeric characters in JavaScript using regular expressions.
var str = '12345';
var isNumeric = /^[0-9]+$/.test(str); // isNumeric will be true
You can convert a string to title case in JavaScript by capitalizing the first letter of each word.
function toTitleCase(str) {
return str.toLowerCase().replace(/(?:^|\s)\w/g, function(match) {
return match.toUpperCase();
});
}
var titleCaseStr = toTitleCase('hello world'); // titleCaseStr will be 'Hello World'
You can remove non-alphanumeric characters from a string in JavaScript using regular expressions.
var str = 'hello123@world!';
var alphanumericStr = str.replace(/[^a-zA-Z0-9]/g, ''); // alphanumericStr will be 'hello123world'
You can remove a specific character from a string in
JavaScript using the replace() method.
var str = 'hello world';
var removedCharStr = str.replace('o', ''); // removedCharStr will be 'hell world'
You can find the longest word in a string in JavaScript by splitting the string into words and then iterating over them to find the longest word.
function findLongestWord(str) {
var words = str.split(' ');
var longestWord = '';
for (var i = 0; i < words.length; i++) {
if (words[i].length > longestWord.length) {
longestWord = words[i];
}
}
return longestWord;
}
var longest = findLongestWord('The quick brown fox jumps over the lazy dog'); // longest will be 'quick'
You can check if two strings are anagrams in JavaScript by comparing their sorted characters.
function areAnagrams(str1, str2) {
return str1.split('').sort().join('') === str2.split('').sort().join('');
}
var result = areAnagrams('listen', 'silent'); // result will be true
You can check if a string is a palindrome in JavaScript by comparing it to its reverse.
function isPalindrome(str) {
return str === str.split('').reverse().join('');
}
var result = isPalindrome('radar'); // result will be true
You can count the occurrences of a substring within a string in JavaScript using regular expressions or by iterating over the string.
function countOccurrences(str, subStr) {
return str.split(subStr).length - 1;
}
var count = countOccurrences('hello world hello', 'hello'); // count will be 2
You can remove duplicate characters from a string in JavaScript by iterating over the string and maintaining a set of unique characters.
function removeDuplicates(str) {
var uniqueChars = '';
for (var i = 0; i < str.length; i++) {
if (uniqueChars.indexOf(str[i]) === -1) {
uniqueChars += str[i];
}
}
return uniqueChars;
}
var result = removeDuplicates('hello world'); // result will be 'helo wrd'