0

I'm trying to figure out the best way to refactor the javascript replace method. I will need to call this same method on many different variables and am unsure of the best practices for refactoring.

function profitMargin(){
var revenue = jQuery("#revenue").val().replace(/[^\d.-]/g, '');
var profit = jQuery("#profit").val().replace(/[^\d.-]/g, '');
var profitMar = (profit/revenue*100).toFixed(4);
1
  • You can always create a new function. Say, dropNumericPrefix Commented Jul 6, 2014 at 2:18

3 Answers 3

1

If you want to avoid having to repeat the same regular expression everywhere you can put that in a variable:

var reNonNumeric = /[^\d.-]/g;
// and then later
var revenue = jQuery("#revenue").val().replace(reNonNumeric, '');
var profit = jQuery("#profit").val().replace(reNonNumeric, '');
// etc.

That makes your code a bit more efficient in that it only creates one regex object, and a bit more descriptive (depending on how you name the variable).

Or you could create a function to do that type of replacement:

function removeNonNumericCharacters(val) {
  return val.replace(/[^\d.-]/g, '');
}

// which you'd use later with:
var revenue = removeNonNumericCharacters( jQuery("#revenue").val() );
var profit = removeNonNumericCharacters( jQuery("#profit").val() );

Note that either way your revenue and profit variables will contain strings. The / operator converts its operands to numbers, but the regex replace you're doing doesn't actually assure that such conversion is possible: the user may have entered "-..-", which your regex would accept but which obviously isn't a valid number.

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

Comments

0
String.prototype.yourFunction = function () {
    return this.replace(/[^\d.-]/g, '');
}

var revenue = jQuery("#revenue").val().yourFunction();

Hope this can help you.

Comments

0

In addition to @nnnnnn's answer, you can also store jquery elements in variables to avoid to find them in the DOM each time you call the function.

var $revenue = jQuery("#revenue"),
    $profit = jQuery("#profit");



// Later in your function
var revenue = $revenue.val().replace(/[^\d.-]/g, '');
var profit = $profit.val().replace(/[^\d.-]/g, '');

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.