Software Training and Placement Center
Strings and Its Operations
In JavaScript, a string is a sequence of characters enclosed within single or double quotes. It represents
text data and is one of the primitive data types in the language.
String Operations:
String operations involve manipulating or working with strings. This includes tasks such as
concatenation, splitting, extracting substrings, replacing characters, converting case, and more.
Code :
let str1 = "Hello";
let str2 = "World";
let combinedStr = str1 + " " + str2; // String concatenation
console.log(combinedStr); // Output: Hello World
String Methods:
JavaScript provides numerous built-in methods for performing operations on strings. These methods
offer functionalities like searching within strings, extracting parts of strings, converting cases, trimming
whitespace, and more.
Code :
let sentence = "JavaScript is awesome";
console.log(sentence.length); // Length of string
console.log(sentence.toUpperCase()); // Convert to uppercase
console.log(sentence.includes("awesome")); // Check substring presence
console.log(sentence.split(" ")); // Split string into array by space
String Operators and Concatenation:
String operators are used for string concatenation, comparison, and manipulation. Concatenation is the
process of combining two or more strings into one.
Code:
let firstName = "John";
let lastName = "Doe";
let fullName = firstName + " " + lastName; // String concatenation
console.log(fullName); // Output: John Doe
Address : ByteSplash Training and Placement Center, 4th Floor, No 92/9, PR Layout, Marathahalli, Bengaluru, Karnataka, 560037
Mobile : +91 8660803099 / +91 6301062858 , Email : [email protected]
Software Training and Placement Center
String to Array and Array to String Conversations:
JavaScript provides methods for converting strings to arrays and vice versa. This conversion is useful for
tasks like splitting a string into substrings or joining array elements into a single string.
Code :
let str = "apple,banana,grape";
let arr = str.split(","); // Convert string to array
console.log(arr); // Output: ["apple", "banana", "grape"]
let newStr = arr.join("-"); // Convert array to string
console.log(newStr); // Output: apple-banana-grape
Basic Coding Questions on Strings:
Basic coding questions on strings often involve tasks such as checking for substring presence, reversing
strings, finding the length of strings, counting occurrences of characters, and so on.
1. Reverse a String
Question: Write a function to reverse a given string.
Code :
function reverseString(str) {
return str.split("").reverse().join("");
}
// Test the function
console.log(reverseString("hello")); // Output: olleh
2. Check Palindrome
Question: Write a function to determine if a string is a palindrome (reads the same forwards
and backwards).
Code :
function isPalindrome(str) {
const reversed = str.split("").reverse().join("");
return str === reversed;
}
// Test the function
console.log(isPalindrome("racecar")); // Output: true
console.log(isPalindrome("hello")); // Output: false
3. Count Vowels
Question: Write a function to count the number of vowels in a string.
Address : ByteSplash Training and Placement Center, 4th Floor, No 92/9, PR Layout, Marathahalli, Bengaluru, Karnataka, 560037
Mobile : +91 8660803099 / +91 6301062858 , Email : [email protected]
Software Training and Placement Center
Code :
function countVowels(str) {
const vowels = 'aeiou';
let count = 0;
for (let char of str.toLowerCase()) {
if (vowels.includes(char)) {
count++;
}
}
return count;
}
// Test the function
console.log(countVowels("hello")); // Output: 2
4. Capitalize Words
Question: Write a function to capitalize the first letter of each word in a sentence.
Code :
function capitalizeWords(sentence) {
return sentence.split(" ").map(word => word.charAt(0).toUpperCase()
+ word.slice(1)).join(" ");
}
// Test the function
console.log(capitalizeWords("hello world")); // Output: Hello
World
5. Check Anagrams
Question: Write a function to check if two strings are anagrams of each other.
Code :
function areAnagrams(str1, str2) {
const sortedStr1 = str1.split("").sort().join("");
const sortedStr2 = str2.split("").sort().join("");
return sortedStr1 === sortedStr2;
}
// Test the function
console.log(areAnagrams("listen", "silent")); // Output: true
console.log(areAnagrams("hello", "world")); // Output: false
6. Find Longest Word
Question: Write a function to find the longest word in a sentence.
Address : ByteSplash Training and Placement Center, 4th Floor, No 92/9, PR Layout, Marathahalli, Bengaluru, Karnataka, 560037
Mobile : +91 8660803099 / +91 6301062858 , Email : [email protected]
Software Training and Placement Center
Code :
function longestWord(sentence) {
const words = sentence.split(" ");
let longest = words[0];
for (let word of words) {
if (word.length > longest.length) {
longest = word;
}
}
return longest;
}
// Test the function
console.log(longestWord("hello world")); // Output: hello
7. Remove Duplicates
Question: Write a function to remove duplicate characters from a string.
Code :
function removeDuplicates(str) {
let result = "";
for (let char of str) {
if (result.indexOf(char) === -1) {
result += char;
}
}
return result;
}
// Test the function
console.log(removeDuplicates("hello")); // Output: helo
8. Count Characters
Question: Write a function to count the occurrences of each character in a string.
Code:
function countCharacters(str) {
const charCount = {};
for (let char of str) {
charCount[char] = (charCount[char] || 0) + 1;
}
return charCount;
}
Address : ByteSplash Training and Placement Center, 4th Floor, No 92/9, PR Layout, Marathahalli, Bengaluru, Karnataka, 560037
Mobile : +91 8660803099 / +91 6301062858 , Email : [email protected]
Software Training and Placement Center
// Test the function
console.log(countCharacters("hello")); // Output: { h: 1, e: 1, l: 2,
o: 1 }
9. Replace Spaces
Question: Write a function to replace all spaces in a string with '%20'.
Code :
function replaceSpaces(str) {
return str.replace(/\s/g, '%20');
}
// Test the function
console.log(replaceSpaces("hello world")); // Output: hello%20world
10. Title Case
Question: Write a function to convert the first letter of each word in a sentence to uppercase.
Code :
function titleCase(sentence) {
return sentence.toLowerCase().replace(/(^|\s)\w/g, (match) =>
match.toUpperCase());
}
// Test the function
console.log(titleCase("hello world")); // Output: Hello World
11. Find Substring
Question: Write a function to check if a substring exists within a given string.
Code :
function hasSubstring(str, substr) {
return str.includes(substr);
}
// Test the function
console.log(hasSubstring("hello world", "world")); // Output: true
console.log(hasSubstring("hello world", "planet")); // Output: false
12. Remove Whitespace
Question: Write a function to remove all whitespace from a string.
Address : ByteSplash Training and Placement Center, 4th Floor, No 92/9, PR Layout, Marathahalli, Bengaluru, Karnataka, 560037
Mobile : +91 8660803099 / +91 6301062858 , Email : [email protected]
Software Training and Placement Center
Code :
function removeWhitespace(str) {
return str.replace(/\s/g, "");
}
// Test the function
console.log(removeWhitespace("hello world")); // Output: helloworld
13. Check Subsequence
Question: Write a function to check if a given string is a subsequence of another string.
Code :
function isSubsequence(sub, str) {
let subIndex = 0;
for (let char of str) {
if (char === sub[subIndex]) {
subIndex++;
}
if (subIndex === sub.length) {
return true;
}
}
return false;
}
// Test the function
console.log(isSubsequence("abc", "ahbgdc")); // Output: true
console.log(isSubsequence("axc", "ahbgdc")); // Output: false
14. Find First Non-Repeating Character
Question: Write a function to find the first non-repeating character in a string.
Code :
function firstNonRepeatingChar(str) {
const charCount = {};
for (let char of str) {
charCount[char] = (charCount[char] || 0) + 1;
}
for (let char of str) {
if (charCount[char] === 1) {
return char;
}
}
return null;
Address : ByteSplash Training and Placement Center, 4th Floor, No 92/9, PR Layout, Marathahalli, Bengaluru, Karnataka, 560037
Mobile : +91 8660803099 / +91 6301062858 , Email : [email protected]
Software Training and Placement Center
// Test the function
console.log(firstNonRepeatingChar("hello")); // Output: h
console.log(firstNonRepeatingChar("hello world")); // Output: h
console.log(firstNonRepeatingChar("aabbcc")); // Output: null
15. Check Rotation
Question: Write a function to check if one string is a rotation of another string.
Code :
function isRotation(str1, str2) {
if (str1.length !== str2.length) {
return false;
}
const combinedStr = str1 + str1;
return combinedStr.includes(str2);
}
// Test the function
console.log(isRotation("waterbottle", "erbottlewat")); // Output: true
console.log(isRotation("hello", "world")); // Output: false
16. . Count Words
Question: Write a function to count the number of words in a sentence.
Code :
function countWords(sentence) {
return sentence.split(" ").filter(word => word !== "").length;
}
// Test the function
console.log(countWords("Hello world")); // Output: 2
console.log(countWords("How are you today?")); // Output: 4
Real-Time Usage of Strings:
Strings are extensively used in web development, data processing, text manipulation, form validation,
user authentication, error handling, and various other scenarios in real-time applications.
Form Validation: Checking input format (e.g., email validation).
Address : ByteSplash Training and Placement Center, 4th Floor, No 92/9, PR Layout, Marathahalli, Bengaluru, Karnataka, 560037
Mobile : +91 8660803099 / +91 6301062858 , Email : [email protected]
Software Training and Placement Center
Data Processing: Parsing and manipulating data from APIs.
User Authentication: Handling passwords and credentials.
Search Functionality: Implementing search features in web applications.
Error Handling: Displaying user-friendly error messages.
Text Manipulation: Formatting text on UI (e.g., capitalizing names).
Localization: Displaying content in different languages.
URL Manipulation: Parsing URLs and extracting information.
Data Storage: Storing serialized data in databases or local storage.
These examples demonstrate how strings are used and manipulated in JavaScript, along with their real-
time applications in various scenarios. Strings are a fundamental part of programming and play a crucial
role in web development and application building.
Address : ByteSplash Training and Placement Center, 4th Floor, No 92/9, PR Layout, Marathahalli, Bengaluru, Karnataka, 560037
Mobile : +91 8660803099 / +91 6301062858 , Email : [email protected]