Variable with regex not matching with a space in user input

I’m currently trying to create a conversion tool to let people convert recipes based on the serving size they would like.

That said, I’m coming across an issue with trying to match the letters entered. Basically, if the user inputs some letters in the input, I want to return those in the result.

For example, someone types in 1/2 Cup Flour, that might return 1 Cup Flour.

In this example, you would extract the “Cup Flour” text and return that in the new value with the number.

I was originally going to use some code sort of like this to do this to output the result:

// Extract Words
   var letters = originalMeasurementsString.match(/[a-zA-Z\s]/g);

$('#resizedMeasurements').html(resizedWholeNumber + resizedDecimal + letters.join(''));

In the code below, I’ve got 3 main different if/else statements, each correlating with different statements within those to check other various conditions met for the type of fraction:

// Checks For Mixed Fraction User Input - For Example: 1 1/2 Cup
if (originalMeasurements.includes(' ')) {
}

// Checks For Single Fraction User Input - For Example: 1/2 Cup
else if (originalMeasurements.includes("https://stackoverflow.com/")) {
}

// Then the Final Else Statement for a Whole Number User Input - For Example: 1 Cup

This solution works for the Mixed Fraction, due to the fact the if statement is checking for a space.

It also works fine for a single fraction if you input for example 1/2cup. The problem is how to get around the fact I want my user to be able to include a space, for example, they might type 1/2 cup instead.

Since the \s in the .match() function /[a-zA-Z\s]/g is supposed to look for white spaces, I’m a bit confused why this is not resulting in the single fraction statement working with a space in the user input.

Does anyone have any alternative strategies to suggest on how I might go about adapting this code to accept a user input with spaces?

I also tried adapting the else if statement above to first check for the / then placed an if statement within that to check for a blank space ‘ ‘, but that didn’t work either.

In addition, another approach I took was combining the statements, for example:

 else if (originalMeasurements.includes("https://stackoverflow.com/") && originalMeasurements.includes(' ')) {}

But that didn’t work either.

Full Code:
https://codepen.io/JoyfullyDeveloped/pen/qBgVjer

if (originalMeasurements.includes(' ')) {
}


else if (originalMeasurements.includes("https://stackoverflow.com/")) {
originalMeasurements = originalMeasurements.replace(' ', '')
}

?

Leave a Comment