2

How can I remove all text characters (not numbers or float) from a javascript variable ?

function deduct(){
    var getamt= document.getElementById('cf').value; //eg: "Amount is 1000"
    var value1 = 100;
    var getamt2 = (value1-getamt);
    document.getElementById('rf').value=getamt2;
}

I want getamt as number. parseInt is giving NaN result.

4
  • var getamt2 = (value1 - Number(getamt)); Commented Feb 20, 2015 at 17:05
  • @epascarello eg: "Amount is 1000" Commented Feb 20, 2015 at 17:10
  • 2
    possible duplicate of strip non-numeric characters from string -- See second answer getamt.replace(/[^\d.-]/g, '') Commented Feb 20, 2015 at 17:11
  • 1
    Note that you need to see one of the non-accepted answers on the dupe to handle floats Commented Feb 20, 2015 at 17:12

2 Answers 2

6

You can replace the non-numbers

    var str = "Amount is 1000";
    var num = +str.replace(/[^0-9.]/g,"");
    console.log(num);

or you can match the number

    var str = "Amount is 1000";
    var match = str.match(/([0-9.])+/,"");
    var num = match ? +match[0] : 0;
    console.log(num);

The match could be more specific too

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

Comments

2

Use regular expression like this:

var getamt= document.getElementById('cf').value; //eg: Amount is 1000
var value1 = 100;
var getamt2 = value1 - getamt.replace( /\D+/g, ''); // this replaces all non-number characters in the string with nothing.
console.log(getamt2);

Try this Fiddle

1 Comment

This only removes the non numeric values from the start of the string, not the middle or end

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.