How do i remove all characters in a string Javascript?
-
14-06-2021 - |
Question
I have a form that sends money value e.g
<input type="text" name="amount" value="N50,000.00 NGN" />
<input type="button" value="submit">
I want to remove all characters in the amount field leaving only the numbers in this format;
<input type="text" name="amount" value="50000" />
<input type="button" value="submit">
what is the best method to do this with javascript?
Solution
first think you want to do is to strip the string or value from numbers using something like this
<input type="text" name="amount" value="N50,000.00 NGN" />
<input type="button" value="submit">
var amount = $('input[name=amount]').val().replace(/[A-Za-z$-]/g, "");
amount=amount.replace(",", "");
amount=parseInt(amount).toFixed(0);
here is a working example
OTHER TIPS
Use
Number('N50,000.00 NGN'.replace(/[a-z, ]/gi,''));
If you want only the integer part, use:
parseInt(Number('N50,000.00 NGN'.replace(/[a-z, ]/gi,'')),10);
The replace
part removes all alphabetic characters, the comma and spaces from the string first.
try this
var i = "N50,000.00 NGN";
parseInt(i.replace(/[^\d\.]/gi, ""), 10);
online example : http://jsbin.com/ojumir
You could try going through the string and take the characters that are digits and append them to a result string. I don't know if that's the best method, but it's one that works.
var res = "";
for (var c in str) { if (str[c].match(/\d/)) { res += str[c]; } }
Try this
<script type="text/javascript" language="javascript">
function doWork() {
var amount = document.getElementsByName('amount');
var str = amount[0].value;
var temp = '';
for (i = 0; i < str.length; i++) {
if (!isNaN(str[i]))
temp += str[i];
}
amount[0].value = temp;
}
</script>
<input type="text" name="amount" value="N50,000.00 NGN" />
<input type="button" value="submit" onclick="doWork();">
<script type="text/javascript" language="javascript">
function doWork() {
var amount = document.getElementsByName('amount');
amount[0].value = parseInt(amount[0].value.replace(/[^0-9.]/g, "")).toFixed(0);
}
</script>
<input type="text" name="amount" value="N50,000.00 NGN" />
<input type="button" value="submit" onclick="doWork();">
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow