Why this function takes extra space in front while taking an input?
My html.erb file is:
<%= form.text_field :monthly_income, class: 'form-control', required: true, onkeyup: "formatLoanAmount(this)" %>
And my script file is:
function formatLoanAmount(element) {
const formatter = new Intl.NumberFormat('en-US', {
style: 'currency',
currency: 'bdt',
minimumFractionDigits: 0,
maximumFractionDigits: 0,
});
input_value = element.value.toString().replace(/BDT/g, '').replace(/,/g, '');
formatted_number = formatter.format(input_value);
formatted_number = formatted_number.toString().replace(/BDT/g, '');
element.value = formatted_number;
}
I’m tryig to take input as a comma sepetated string and expection an integer as output.
2
Answers
However, you can use trim() function to remove whitespaces if exits. Here is the updated version of your code.
The extra space in front of the input value might be caused by the
replace
method in yourformatLoanAmount
function. Specifically, thereplace(/BDT/g, '')
part of the code is removing all occurrences of the string "BDT" from the input value. If the input value starts with "BDT", then this will leave an extra space at the beginning of the formatted number.To fix this issue, you can modify the
replace
method to remove all occurrences of "BDT " (with a space after "BDT") instead of just "BDT". Here’s the updated code:This should remove any extra spaces at the beginning of the formatted number.
Additionally, if you want to convert the formatted number back to an integer without commas, you can modify the
formatted_number
variable to remove all commas before assigning it toelement.value
. Here’s the updated code:This should ensure that the input value is converted to an integer without commas after formatting.