0

Reaching out to all the JS regex gurus out there. I am building a function that would remove $, white space, comma, [A-Z], [a-z] from string, leaving only float (if it exists within the string given) something like so:

var result = myFunction( 'USD $12, 345.95'); //result = 12345.95
var result = myFunction( 'ten dollars US' ); // result = false

function myFunction( weirdString ){

    // some code

}

I know I can go something like (forgive me if I'm wrong):

weirdString.replace(/[&$<>"'`=\/\s]|[A-Z]|[a-z]/g, '');
isNaN( weirdString ) ? return false : return weirdString;

But what is the right way?

1
  • 2
    No need to separate those square bracket character sets with alternators. You can just use [&$<>"'`=\/ A-Z]a-z]. Also just use a literal space if that's all you're expecting. \s matches any whitespace character. Commented Nov 16, 2017 at 1:40

2 Answers 2

1

Instead of blacklisting every character you don't want to allow, you can kind of whitelist only the characters you need:

[^\d.]  // match anything that isn't a digit or period

The advantage of this is that you don't have to think of every possible character to reject. For example, if for whatever reason, the character é (e with an accent) appears in your string, the regex you were using will consider it as part of the floating point number, which you probably don't want.

Test it here: https://regex101.com/r/g8zBRP/2

Sign up to request clarification or add additional context in comments.

Comments

0

So here's the function I came up with:

function extractFloatFromString( input ){

    var result = input.match( /[\d+.]/g );
    return result == null ? 0 : result.join('');

}

https://jsfiddle.net/7hq1dcwn/3/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.