I am writing a Javascript function to recognise the blanks (represented by four underscores) a user has filled in a string. For instance, when given the template ____ world
, and the user's input of Hello world
, it should return the array ["Hello"]
.
So far, I've cobbled together the below, but it has issues identifying the blanks
function identifyBlanks(template, filledString) {
// Split the template and filled string into arrays of words
const templateWords = template.split(' ');
const filledWords = filledString.split(' ');
// Initialize an array to store the filled words
const filledBlanks = [];
// Iterate over the template and check for blanks
for (let i = 0; i < templateWords.length; i++) {
// Check if the template word contains a blank (indicated by multiple underscores)
if (templateWords[i].includes('____')) {
const blankIndex = templateWords[i].indexOf('____');
// Find the corresponding filled word by matching the substring before and after the blank
const filledWord = filledWords.find(word => {
const wordBeforeBlank = word.substring(0, blankIndex);
const wordAfterBlank = word.substring(blankIndex + 4); // 4 represents the length of '____'
return templateWords[i].startsWith(wordBeforeBlank) && templateWords[i].endsWith(wordAfterBlank);
});
// Add the filled word to the array if found
if (filledWord) {
filledBlanks.push(filledWord);
}
}
}
return filledBlanks;
}
const template = "letters a____c";
const filledString = "letters abc";
const filledBlanks = identifyBlanks(template, filledString);
console.log(filledBlanks); // Output: ["b"]
There's a couple more edge cases I'm struggling with too - it should be able to recognise when a blank has been replaced by an empty string, as well as detecting blanks that are inside words, instead of surrounded by spaces. For instance, when given the template H____o ____ world!
and the string Hello world!
, it should return ["ell", ""]
edit: The use case for this is to be able to reverse engineer a user's answer to a Python problem, where they are given a problem like
____ = ____("Enter your name")
____(name)
and could answer it like
name = input("Enter your name")
print(name)
I then need to get the blanks they've entered at a later time. I'm aware there are better ways of implementing this (e.g. storing just the blanks they've entered, as opposed to their whole solution), but in the context of the system it's part of this isn't feasible.