I need help removing trailing non-numerical characters when converting a string to a number

I’m presently working on a JavaScript project that requires me to transform user-supplied strings to integers. However, I’ve run across a problem when the input text includes non-numeric characters following the number.

Here’s an example of my code:

function convertToNumber(input) {
    return parseFloat(input);
}

let userInput = "42abc";
let result = convertToNumber(userInput);

console.log("User input:", userInput);
console.log("Converted result:", result);

My goal is to extract the numeric portion of the text and convert it to a number, similar to the example given in this post by scaler, but ignoring any following non-numeric characters. In this situation, I expected a result of 42, but instead received:

User input: 42abc
Converted result: 42

The parseFloat() method appears to terminate the conversion as soon as it reaches non-numeric characters. How can I change the code so that just the numeric portion of the string is used during the conversion?

Any advice on how to handle this scenario would be greatly appreciated.

From my view here, it seems like the code is already doing what you wanted, could you show more test cases so we could see the issue better?

3 Likes