0% found this document useful (0 votes)
29 views5 pages

JavaScript String Function Examples

The document contains 15 questions about writing JavaScript functions to perform string operations and manipulation tasks. For each question, it provides the function description, suggested file name, test data and the code implementation of the function. The questions cover common string tasks like checking if a string is empty, splitting a string into an array, extracting characters, parameterizing strings, changing case, concatenating strings, inserting strings and counting/searching substrings.

Uploaded by

vijaymuttevi
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
29 views5 pages

JavaScript String Function Examples

The document contains 15 questions about writing JavaScript functions to perform string operations and manipulation tasks. For each question, it provides the function description, suggested file name, test data and the code implementation of the function. The questions cover common string tasks like checking if a string is empty, splitting a string into an array, extracting characters, parameterizing strings, changing case, concatenating strings, inserting strings and counting/searching substrings.

Uploaded by

vijaymuttevi
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

// Q1. Write a JavaScript function to check whether a string is blank or not?

// File name suggestion: [Link]


// Test Data :
// [Link](isBlank('')); // true
// [Link](isBlank('abc')); // false
const isBlank = input => ![Link];
[Link](isBlank('')); // true
[Link](isBlank('abc')); // false

// Q2. Write a JavaScript function to split a string (sentence) and convert it into an
array of words?
// File name suggestion: [Link]
// Test Data :
// [Link](stringToArray("Robin Singh")); // ["Robin", "Singh"]
const stringToArray = str => [Link](' ');
[Link](stringToArray('Robin Singh')); // ["Robin", "Singh"]

// Q3. Write a JavaScript function to extract a specified number of characters from a


string?
// File name suggestion: [Link]
// Test Data :
// [Link](truncateString("Robin Singh", 4)); // "Robi"
const truncateString = (str, length) => [Link](0, length);
[Link](truncateString('Robin Singh', 4)); // "Robi"

// Q4. Write a JavaScript function to parameterize a string?


// File name suggestion: [Link]
// Test Data :
// [Link](stringParameterize("Robin Singh from USA.")); // "robin-singh-from-
usa"
const stringParameterize = str => [Link]().replace(/\s/g, '-');
[Link](stringParameterize('Robin Singh from USA.')); // "robin-singh-from-usa"

// Q5. Write a JavaScript function to capitalize the first letter of a string?


// File name suggestion: [Link]
// Test Data :
// [Link](capitalize('js string exercises')); // "Js string exercises"
const capitalize = str => `${[Link](0).toUpperCase()}${[Link](1)}`;
[Link](capitalize('js string exercises')); // "Js string exercises"

// Q6. Write a JavaScript function to capitalize the first letter of each word in a string?
// File name suggestion: [Link]
// Test Data :
// [Link](capitalizeWords('js string exercises')); // "Js String Exercises"
const capitalizeWords = str =>
str
.split(' ')
.map(word => `${[Link](0).toUpperCase()}${[Link](1)}`)
.join(' ');
[Link](capitalizeWords('js string exercises')); // "Js String Exercises"
// Q7. Write a JavaScript function that takes a string which has lower and upper case
letters as a parameter and converts upper case letters to lower case, and lower case
letters to upper case?
// File name suggestion: [Link]
// Test Data :
// [Link](swapCase('AaBbc')); // "aAbBC"
const swapCase = str => {
let result = '';
for (let i = 0; i < [Link]; i++) {
if (str[i] === str[i].toUpperCase()) {
result += str[i].toLowerCase();
} else {
result += str[i].toUpperCase();
}
}
return result;
};
[Link](swapCase('AaBbc')); // "aAbBC"

// Q8. Write a JavaScript function that takes a string which can have both lower and
upper case letters as a parameter and converts alternate character to upper case &
lower case, starting from upper case?
// File name suggestion: [Link]
// Test Data :
// [Link](alternateCase('samsung')); // "SaMsUnG"
const alternateCase = str => {
let result = '';
for (let i = 0; i < [Link]; i++) {
if (i % 2 === 0) {
result += str[i].toUpperCase();
} else {
result += str[i].toLowerCase();
}
}
return result;
};
[Link](alternateCase('samsung')); // "SaMsUnG"

// Q9. Write a JavaScript function to concatenates a given string n times (default is


1)?
// File name suggestion: [Link]
// Test Data :
// [Link](repeat('Ha!')); // "Ha!"
// [Link](repeat('Ha!',2)); // "Ha!Ha!"
// [Link](repeat('Ha!',3)); // "Ha!Ha!Ha!"
const repeat = (str, len) => {
let result = str;
if (len && len > 1) {
for (let i = 1; i < len; i++) {
result += str;
}
}
return result;
};
[Link](repeat('Ha!')); // "Ha!"
[Link](repeat('Ha!', 2)); // "Ha!Ha!"
[Link](repeat('Ha!', 3)); // "Ha!Ha!Ha!"

// Q10. Write a JavaScript function to insert a string within a string at a particular


position (default is 1)?
// File name suggestion: [Link]
// Test Data :
// [Link](insert('We are doing some exercises.')); // "We are doing some
exercises."
// [Link](insert('We are doing some exercises.','JavaScript ')); // "JavaScript We
are doing some exercises."
// [Link](insert('We are doing some exercises.','JavaScript ',18)); // "We are
doing some JavaScript exercises."
const insert = (str, ins_str, n) => {
if (!n) {
n = 0;
}
if (!ins_str) {
ins_str = '';
}

return `${[Link](0, n)}${ins_str}${[Link](n)}`;


};
[Link](insert('We are doing some exercises.')); // "We are doing some
exercises."
[Link](insert('We are doing some exercises.', 'JavaScript ')); // "JavaScript We
are doing some exercises."
[Link](insert('We are doing some exercises.', 'JavaScript ', 18)); // "We are
doing some JavaScript exercises."

// Q11. Write a JavaScript function to chop a string into chunks of a given length?
// File name suggestion: [Link]
// Test Data :
// [Link](stringChop('w3resource')); // ["w3resource"]
// [Link](stringChop('w3resource',2)); // ["w3", "re", "so", "ur", "ce"]
// [Link](stringChop('w3resource',3)); // ["w3r", "eso", "urc", "e"]
const stringChop = (str, size = 1) => {
const result = [];
let smallStr = '';
for (let char of str) {
if ([Link] === size) {
[Link](smallStr);
smallStr = '';
}
smallStr += char;
}
if ([Link]) {
[Link](smallStr);
}
return result;
};
[Link](stringChop('w3resource')); // ["w3resource"]
[Link](stringChop('w3resource', 2)); // ["w3", "re", "so", "ur", "ce"]
[Link](stringChop('w3resource', 3)); // ["w3r", "eso", "urc", "e"]

// Q12. Write a JavaScript function to count the occurrence of a substring in a string?


// File name suggestion: [Link]
// Test Data :
// [Link](count("The quick brown fox jumps over the lazy dog", 'the')); // 2
const count = (text, word) => {
let count = 0,
index;
text = [Link]();
word = [Link]();
while (index !== -1) {
index = [Link](word, index);
if (index !== -1) {
count++;
index++;
}
}
return count;
};
[Link](count('The quick brown fox jumps over the lazy dog', 'the')); // 2

// Q13. Write a JavaScript function to find a word within a string?


// File name suggestion: [Link]
// Test Data :
// [Link](searchWord('The quick brown fox', 'fox')); // "'fox' was found 1 times."
// [Link](searchWord('aa, bb, cc, dd, aa', 'aa')); // "'aa' was found 2 times."
const searchWord = (text, word) => {
let count = 0,
index;
text = [Link]();
word = [Link]();
while (index !== -1) {
index = [Link](word, index);
if (index !== -1) {
count++;
index++;
}
}
return `'${word}' was found ${count} times.`;
};
[Link](searchWord('The quick brown fox', 'fox')); // "'fox' was found 1 times."
[Link](searchWord('aa, bb, cc, dd, aa', 'aa')); // "'aa' was found 2 times."

// Q14. Write a JavaScript function to test whether the character at the provided
(character) index is upper case?
// File name suggestion: [Link]
// Test Data :
// [Link](isUpperCaseAt('Js STRING EXERCISES', 1)); // false
const isUpperCaseAt = (str, index) => str[index].toUpperCase() === str[index];
[Link](isUpperCaseAt('Js STRING EXERCISES', 1)); // false

// Q15. Write a JavaScript function to test whether the character at the provided
(character) index is upper case?
// File name suggestion: [Link]
// Test Data :
// [Link](isLowerCaseAt('Js STRING EXERCISES', 1)); // true
const isLowerCaseAt = (str, index) => str[index].toLowerCase() === str[index];
[Link](isLowerCaseAt('Js STRING EXERCISES', 1)); // true

Common questions

Powered by AI

Alternating character casing can enhance text emphasis and style in digital media. The function `alternateCase` processes the string by toggling between uppercase for even indices and lowercase for odd indices, achieving the visual effect through conditional checks on character positions during iteration .

This function can be used in parsing data, structuring large textual content for analysis, or even UI display logic for pagination. The `stringChop` leverages a loop to iterate through the string, collecting characters into segments of defined sizes and pushing these into an array upon reaching the desired length, or when the iteration ends .

This function helps standardize user input, such as names or titles, by ensuring that each word begins with an uppercase letter, improving readability and presentation consistency. The function `capitalizeWords` employs `split`, `map`, and `join` methods to transform each word in the string, using `charAt(0).toUpperCase()` and `slice(1)` on each word .

The JavaScript function to check if a string is blank uses the length property of the string to see if it is zero. The function uses the expression `!input.length` to determine if the string's length is zero. This is important because a string is considered blank if it has no characters, which is indicated by its length being zero .

Altering the case of text can significantly affect its readability and visual appeal, drawing user attention or adhering to design aesthetics. The function `swapCase` iterates over the string's characters and switches their case with `toUpperCase()` and `toLowerCase()` based on the current case of each character .

The function `repeat` concatenates a string by iteratively appending it to a result string, which facilitates easy and swift repetition of strings. This simplicity in design is effective for straightforward tasks and reduces computational overhead with minimal logic, making it advantageous for performance optimization in scenarios requiring repetitive text patterns .

The function `stringToArray` helps in text manipulation by converting a single string into an array of words, making it easier to perform operations on individual words. It uses the `split` method with a space (' ') as a delimiter to separate the words in the string .

The function `truncateString` utilizes the `substr` method to extract a specified number of characters from the beginning of a string. This functionality is useful in web development when presenting snippets or previews of longer text content, ensuring that displayed text fits within a limited space or layout .

The benefits include creating URL-friendly strings, making urls easier to use in web development. The function `stringParameterize` uses the `toLowerCase` method and a regular expression `/\s/g` to replace spaces with hyphens, converting it into a parameterized format .

Inserting strings at specific positions is crucial for templating or building dynamic, user-customized content in web applications. The function `insert` achieves this by leveraging `slice` to merge the original string with the insertion at the desired location, offering dynamic string manipulation capabilities .

You might also like