Skip to content

Instantly share code, notes, and snippets.

@adarsh-chakraborty
Created January 16, 2023 16:56
Show Gist options
  • Save adarsh-chakraborty/7a0dfd82414e658e1a1333e4b7733939 to your computer and use it in GitHub Desktop.
Save adarsh-chakraborty/7a0dfd82414e658e1a1333e4b7733939 to your computer and use it in GitHub Desktop.
Write a function that takes two strings (a and b) as arguments. Return the number of times a occurs in b.
/*
Write a function that takes two strings (a and b) as arguments. Return the number of times a occurs in b.
Test Cases:
myFunction('m', 'how many times does the character occur in this sentence?')
Expected 2
myFunction('h', 'how many times does the character occur in this sentence?')
Expected 4
myFunction('?', 'how many times does the character occur in this sentence?')
Expected 1
myFunction('z', 'how many times does the character occur in this sentence?')
Expected 0
Using JavaScript Search methods
*/
function search(a,b){
if(!a || !b){
throw new Error("Missing arguements, Both arguements required.");
}
const subStr = a.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
const re = new RegExp(subStr, "gi");
return (b.match(re) || []).length
}
// Test cases
{
// Test Case 1: Expected 2
const expected = 2;
const result = search('m', 'how many times does the character occur in this sentence?');
console.log('Test case 1:', result === expected ? 'Passed': 'Failed');
}
{
// Expected 4
const expected = 4;
const result =search('h', 'how many times does the character occur in this sentence?')
console.log('Test case 2:', result === expected ? 'Passed': 'Failed');
}
{
// Expected 1
const expected = 1;
const result =search('?', 'how many times does the character occur in this sentence?')
console.log('Test case 3:', result === expected ? 'Passed': 'Failed');
}
{
const expected = 0;
const result = search('z', 'how many times does the character occur in this sentence?');
console.log('Test case 4:', result === expected ? 'Passed': 'Failed');
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment