How to format a phone number with jQuery - javascript

I'm currently displaying phone numbers like 2124771000. However, I need the number to be formatted in a more human-readable form, for example: 212-477-1000. Here's my current HTML:
<p class="phone">2124771000</p>

Simple: http://jsfiddle.net/Xxk3F/3/
$('.phone').text(function(i, text) {
return text.replace(/(\d{3})(\d{3})(\d{4})/, '$1-$2-$3');
});
Or: http://jsfiddle.net/Xxk3F/1/
$('.phone').text(function(i, text) {
return text.replace(/(\d\d\d)(\d\d\d)(\d\d\d\d)/, '$1-$2-$3');
});
Note: The .text() method cannot be used on input elements. For input field text, use the .val() method.

var phone = '2124771000',
formatted = phone.substr(0, 3) + '-' + phone.substr(3, 3) + '-' + phone.substr(6,4)

Don't forget to ensure you are working with purely integers.
var separator = '-';
$( ".phone" ).text( function( i, DATA ) {
DATA
.replace( /[^\d]/g, '' )
.replace( /(\d{3})(\d{3})(\d{4})/, '$1' + separator + '$2' + separator + '$3' );
return DATA;
});

Here's a combination of some of these answers. This can be used for input fields. Deals with phone numbers that are 7 and 10 digits long.
// Used to format phone number
function phoneFormatter() {
$('.phone').on('input', function() {
var number = $(this).val().replace(/[^\d]/g, '')
if (number.length == 7) {
number = number.replace(/(\d{3})(\d{4})/, "$1-$2");
} else if (number.length == 10) {
number = number.replace(/(\d{3})(\d{3})(\d{4})/, "($1) $2-$3");
}
$(this).val(number)
});
}
Live example: JSFiddle
I know this doesn't directly answer the question, but when I was looking up answers this was one of the first pages I found. So this answer is for anyone searching for something similar to what I was searching for.

Use a library to handle phone number. Libphonenumber by Google is your best bet.
// Require `PhoneNumberFormat`.
var PNF = require('google-libphonenumber').PhoneNumberFormat;
// Get an instance of `PhoneNumberUtil`.
var phoneUtil = require('google-libphonenumber').PhoneNumberUtil.getInstance();
// Parse number with country code.
var phoneNumber = phoneUtil.parse('202-456-1414', 'US');
// Print number in the international format.
console.log(phoneUtil.format(phoneNumber, PNF.INTERNATIONAL));
// => +1 202-456-1414
I recommend to use this package by seegno.

try something like this..
jQuery.validator.addMethod("phoneValidate", function(number, element) {
number = number.replace(/\s+/g, "");
return this.optional(element) || number.length > 9 &&
number.match(/^(1-?)?(\([2-9]\d{2}\)|[2-9]\d{2})-?[2-9]\d{2}-?\d{4}$/);
}, "Please specify a valid phone number");
$("#myform").validate({
rules: {
field: {
required: true,
phoneValidate: true
}
}
});

I have provided jsfiddle link for you to format US phone numbers as
(XXX) XXX-XXX
$('.class-name').on('keypress', function(e) {
var key = e.charCode || e.keyCode || 0;
var phone = $(this);
if (phone.val().length === 0) {
phone.val(phone.val() + '(');
}
// Auto-format- do not expose the mask as the user begins to type
if (key !== 8 && key !== 9) {
if (phone.val().length === 4) {
phone.val(phone.val() + ')');
}
if (phone.val().length === 5) {
phone.val(phone.val() + ' ');
}
if (phone.val().length === 9) {
phone.val(phone.val() + '-');
}
if (phone.val().length >= 14) {
phone.val(phone.val().slice(0, 13));
}
}
// Allow numeric (and tab, backspace, delete) keys only
return (key == 8 ||
key == 9 ||
key == 46 ||
(key >= 48 && key <= 57) ||
(key >= 96 && key <= 105));
})
.on('focus', function() {
phone = $(this);
if (phone.val().length === 0) {
phone.val('(');
} else {
var val = phone.val();
phone.val('').val(val); // Ensure cursor remains at the end
}
})
.on('blur', function() {
$phone = $(this);
if ($phone.val() === '(') {
$phone.val('');
}
});
Live example: JSFiddle

Quick roll your own code:
Here is a solution modified from Cruz Nunez's solution above.
// Used to format phone number
function phoneFormatter() {
$('.phone').on('input', function() {
var number = $(this).val().replace(/[^\d]/g, '')
if (number.length < 7) {
number = number.replace(/(\d{0,3})(\d{0,3})/, "($1) $2");
} else if (number.length <= 10) {
number = number.replace(/(\d{3})(\d{3})(\d{1,4})/, "($1) $2-$3");
} else {
// ignore additional digits
number = number.replace(/(\d{3})(\d{1,3})(\d{1,4})(\d.*)/, "($1) $2-$3");
}
$(this).val(number)
});
};
$(phoneFormatter);
JSFiddle
In this solution, the formatting is applied no matter how many digits the user has entered. (In Nunes' solution, the formatting is applied only when exactly 7 or 10 digits has been entered.)
It requires the zip code for a 10-digit US phone number to be entered.
Both solutions, however, editing already entered digits is problematic, as typed digits always get added to the end.
I recommend, instead, the robust jQuery Mask Plugin code, mentioned below:
Recommend jQuery Mask Plugin
I recommend using jQuery Mask Plugin (page has live examples), on github.
These links have minimal explanations on how to use:
https://dobsondev.com/2017/04/14/using-jquery-mask-to-mask-form-input/
http://www.igorescobar.com/blog/2012/05/06/masks-with-jquery-mask-plugin/
http://www.igorescobar.com/blog/2013/04/30/using-jquery-mask-plugin-with-zepto-js/
CDN
Instead of installing/hosting the code, you can also add a link to a CDN of the script
CDN Link for jQuery Mask Plugin
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.mask/1.14.16/jquery.mask.min.js" integrity="sha512-pHVGpX7F/27yZ0ISY+VVjyULApbDlD0/X0rgGbTqCE7WFW5MezNTWG/dnhtbBuICzsd0WQPgpE4REBLv+UqChw==" crossorigin="anonymous"></script>
or
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.mask/1.14.16/jquery.mask.js" integrity="sha512-pHVGpX7F/27yZ0ISY+VVjyULApbDlD0/X0rgGbTqCE7WFW5MezNTWG/dnhtbBuICzsd0WQPgpE4REBLv+UqChw==" crossorigin="anonymous"></script>
WordPress Contact Form 7: use Masks Form Fields plugin
If you are using Contact Form 7 plugin on a WordPress site, the easiest option to control form fields is if you can simply add a class to your input field to take care of it for you.
Masks Form Fields plugin is one option that makes this easy to do.
I like this option, as, Internally, it embeds a minimized version of the code from jQuery Mask Plugin mentioned above.
Example usage on a Contact Form 7 form:
<label> Your Phone Number (required)
[tel* customer-phone class:phone_us minlength:14 placeholder "(555) 555-5555"]
</label>
The important part here is class:phone_us.
Note that if you use minlength/maxlength, the length must include the mask characters, in addition to the digits.

Consider libphonenumber-js (https://github.com/halt-hammerzeit/libphonenumber-js) which is a smaller version of the full and famous libphonenumber.
Quick and dirty example:
$(".phone-format").keyup(function() {
// Don't reformat backspace/delete so correcting mistakes is easier
if (event.keyCode != 46 && event.keyCode != 8) {
var val_old = $(this).val();
var newString = new libphonenumber.asYouType('US').input(val_old);
$(this).focus().val('').val(newString);
}
});
(If you do use a regex to avoid a library download, avoid reformat on backspace/delete will make it easier to correct typos.)

An alternative solution:
function numberWithSpaces(value, pattern) {
var i = 0,
phone = value.toString();
return pattern.replace(/#/g, _ => phone[i++]);
}
console.log(numberWithSpaces('2124771000', '###-###-####'));

$(".phoneString").text(function(i, text) {
text = text.replace(/(\d{3})(\d{3})(\d{4})/, "($1) $2-$3");
return text;
});
Output :-(123) 657-8963

I found this question while googling for a way to auto-format phone numbers via a jQuery plugin. The accepted answer was not ideal for my needs and a lot has happened in the 6 years since it was originally posted. I eventually found the solution and am documenting it here for posterity.
Problem
I would like my phone number html input field to auto-format (mask) the value as the user types.
Solution
Check out Cleave.js. It is a very powerful/flexible and easy way to solve this problem, and many other data masking issues.
Formatting a phone number is as easy as:
var cleave = new Cleave('.input-element', {
phone: true,
phoneRegionCode: 'US'
});

Input:
4546644645
Code:
PhoneNumber = Input.replace(/(\d\d\d)(\d\d\d)(\d\d\d\d)/, "($1)$2-$3");
OutPut:
(454)664-4645

Following event handler should do the needful:
$('[name=mobilePhone]').on('keyup', function(e){
var enteredNumberStr=this.$('[name=mobilePhone]').val(),
//Filter only numbers from the input
cleanedStr = (enteredNumberStr).replace(/\D/g, ''),
inputLength=cleanedStr.length,
formattedNumber=cleanedStr;
if(inputLength>3 && inputLength<7) {
formattedNumber= cleanedStr.substr(0,3) + '-' + cleanedStr.substr(3,inputLength-1) ;
}else if (inputLength>=7 && inputLength<10) {
formattedNumber= cleanedStr.substr(0,3) + '-' + cleanedStr.substr(3,3) + '-' + cleanedStr.substr(6,inputLength-1);
}else if(inputLength>=10) {
formattedNumber= cleanedStr.substr(0,3) + '-' + cleanedStr.substr(3,3) + '-' + cleanedStr.substr(6,inputLength-1);
}
console.log(formattedNumber);
this.$('[name=mobilePhone]').val(formattedNumber);
});

To expand on Cruz Nunez code and add continual formatting, plus include some international phone number formats.
$('#phone').on('input', function() {
var number = $(this).val().replace(/[^\d]/g, '');
if (number.length == 3) {
number = number.replace(/(\d{3})/, "$1-");
} else if (number.length == 4) {
number = number.replace(/(\d{3})(\d{1})/, "$1-$2");
} else if (number.length == 5) {
number = number.replace(/(\d{3})(\d{2})/, "$1-$2");
} else if (number.length == 6) {
number = number.replace(/(\d{3})(\d{3})/, "$1-$2-");
} else if (number.length == 7) {
number = number.replace(/(\d{3})(\d{3})(\d{1})/, "$1-$2-$3");
} else if (number.length == 8) {
number = number.replace(/(\d{4})(\d{4})/, "$1-$2");
} else if (number.length == 9) {
number = number.replace(/(\d{3})(\d{3})(\d{3})/, "$1-$2-$3");
} else if (number.length == 10) {
number = number.replace(/(\d{3})(\d{3})(\d{4})/, "$1-$2-$3");
} else if (number.length == 11) {
number = number.replace(/(\d{1})(\d{3})(\d{3})(\d{4})/, "$1-$2-$3-$4");
} else if (number.length == 12) {
number = number.replace(/(\d{2})(\d{3})(\d{3})(\d{4})/, "$1-$2-$3-$4");
}
$(this).val(number);
});

may be this will help
var countryCode = +91;
var phone=1234567890;
phone=phone.split('').reverse().join('');//0987654321
var formatPhone=phone.substring(0,4)+'-';//0987-
phone=phone.replace(phone.substring(0,4),'');//654321
while(phone.length>0){
formatPhone=formatPhone+phone.substring(0,3)+'-';
phone=phone.replace(phone.substring(0,3),'');
}
formatPhone=countryCode+formatPhone.split('').reverse().join('');
you will get +91-123-456-7890

Related

How to sanitize (digits and hyphen only) and auto-format (hyphen and leading zeros insertion) a text input value while typing and/or pasting text?

There are similar questions on SO, but mine is a bit unique. I want to limit an input text field to 9 characters in length (currently solved with maxlength attribute), only allow typing in numeric values and the hyphen character. Sort of handled with this code returning "True":
/^\d*\-?\d*$/.test(value)
Where I'm stuck is, I want the input text field to auto-format the value as the user types in the format:
12345-123
Where it's 5 digits (may have leading zeros or not depending on how user inputs it), followed by a hyphen, then always 3 digits. I'd like it to pad the first 5 with zeros if user enters something like "123-495" manually, so it would become "00123-495".
I'm not sure how to add in the auto-zero padding, or placement of the hyphen automatically.
Not opposed to using jQuery, but would prefer vanilla.
EDIT: Thought it might be useful to add. This is for an access card number entry box. So value will always be a positive number, and will always have 3 digits after the single hyphen. The card number will always be 5-digits in length, but again, may be padded with zeros to make it that length. Ideal output should always be "xxxxx-xxx".
EDIT 2: This seems to work, but there's an issue where user can enter non-numeric characters at first and after the 1st entry, only then does it clear it out. It also doesn't seem to let me hit backspace past the hyphen... Is there a way to prevent it from allowing alpha characters completely?
// Restricts input for the given textbox to the given inputFilter function.
function setInputFilter(textbox, inputFilter) {
["input", "keydown", "keyup", "mousedown", "mouseup", "select", "contextmenu", "drop"].forEach(function(event) {
textbox.addEventListener(event, function() {
if (inputFilter(this.value)) {
// Current value
new_val = '';
if (this.value.includes('-') && this.value.slice(this.value.indexOf('-')).length == 4) {
console.log("Value not hyphenated yet");
pad_needed = 5 - this.value.indexOf('-');
console.log('Pad needed: ' + pad_needed);
new_val = this.value.padStart(9, '0');
this.value = new_val;
} else if (this.value.length >= 5 && this.value.includes('-') && this.value.slice(this.value.indexOf('-')).length == 4) {
if (this.value.slice(5, 1) == '-') {
// Already a hyphen added, just add rest of numbers
new_val = this.value.slice(0, 6) + this.value.slice(6);
} else {
// Needs hyphen added
new_val = this.value.slice(0, 5) + '-' + this.value.slice(6);
}
this.value = new_val;
} else if (this.value.length >= 5 && !this.value.includes('-')) {
// Needs hyphen added
new_val = this.value.slice(0, 5) + '-' + this.value.slice(6);
this.value = new_val;
}
this.oldValue = this.value;
this.oldSelectionStart = this.selectionStart;
this.oldSelectionEnd = this.selectionEnd;
} else if (this.hasOwnProperty("oldValue")) {
this.value = this.oldValue;
this.setSelectionRange(this.oldSelectionStart, this.oldSelectionEnd);
} else {
this.value = "";
}
});
});
}
setInputFilter(document.getElementById("card-number"), function(value) {
return /^\d*\-?\d*$/.test(value); // Allow digits and '-' only
});
function getSanitizedInputValue(value) {
value = value
.trim()
.replace(/^[-]+/, '')
.replace(/[-]+/, '-');
let [
first,
...rest
] = (value.match(/[-\d]+/g) ?? [])
.join('')
.split('-')
let joiner = '';
if (first.length >= 6) {
joiner = '-';
rest.unshift(first.slice(5));
first = first.slice(0, 5);
} else if (rest.length >= 1) {
joiner = '-';
first = first.padStart(5, '0');
}
return [
first,
rest.join(''),
]
.join(joiner)
.slice(0,9);
}
function handleInput({ currentTarget: control }) {
const { value: recentValue, selectionStart, selectionEnd } = control;
const regXHasHyphen = /-/;
const sanitizedValue = getSanitizedInputValue(recentValue);
const sanitizedLength = sanitizedValue.length;
const recentLength = recentValue.length;
const positionDelta = (
(recentLength <= 5) &&
(sanitizedLength >= 6) &&
(sanitizedLength - recentLength)
) || (
!regXHasHyphen.test(recentValue) &&
regXHasHyphen.test(sanitizedValue) &&
1
) || 0;
control.value = sanitizedValue;
control.selectionStart =
Math.min(sanitizedLength, (selectionStart + positionDelta));
control.selectionEnd =
Math.min(sanitizedLength, (selectionEnd + positionDelta));
}
document
.querySelector('[type="text"]')
.addEventListener('input', handleInput);
<input type="text" maxlength="9" />

validate input with decimal precision and scale

I am trying to create a javascript function which is called on keypress event on a input which does the following:
Input should be a valid decimal with format (5,2) => (XXXXX.YY) which are variable to the function. Input is restricted if user adds any value which does not conform to the format above.
If existing input starts with . append 0 to the starting automatically
HTML
<input type="text" onkeypress="return checkDecimal(event, this, 5, 2);" id="price2" value="27.15">
Javascript
function checkDecimal(evt, item, lenBeforeDecimal, lenAfterDecimal) {
var charCode = evt.which;
var trimmed = $(item).val().replace(/\b^0+/g, "");
if(checkStartsWith(trimmed, '.') == true){
trimmed = '0' + trimmed;
}
//Allow following keys
//8 = Backspace, 9 = Tab
if(charCode == 8 || charCode == 9){
return true;
}
//Only a single '.' is to be allowed
if(charCode == 46){
var dotOccurrences = (trimmed.match(/\./g) || []).length;
if(dotOccurrences != undefined && dotOccurrences == 1){
return false;
}else{
return true;
}
}
if (charCode > 31 && ((charCode < 48) || (charCode > 57))) {
return false;
}
if ($(item).val() != trimmed){
$(item).val(trimmed);}
//Check the start and end length
if(trimmed.indexOf('.') == -1){
if(trimmed.length >= parseInt(lenBeforeDecimal)){
return false;
}
}else{
var inputArr = trimmed.split(".");
if(inputArr[0].length > parseInt(lenBeforeDecimal) || inputArr[1].length >= parseInt(lenAfterDecimal)){
return false;
}
}
return true;
}
function checkStartsWith(str, prefix){
return str.indexOf(prefix) === 0;
}
Issues
If user inputs 12345.9 and then moves the caret position after 5, user is able to add another digit before the decimal 123456.9 which should not be allowed.
If user inputs 1.9 and then remove 1 and add 5, 5 is added at the end and the entered value becomes 0.95 and not 5.9
JS Fiddle
Consider using a regular expression like:
/^(\d{0,5}\.\d{0,2}|\d{0,5}|\.\d{0,2})$/;
that allows everything up to and including your required format, but returns false if the number part is more than 5 digits or if the fraction is more than 2 digits, e.g.:
<input type="text" onkeyup="check(this.value)"><span id="er"></span>
<script>
function check(v) {
var re = /^(\d{0,5}\.\d{0,2}|\d{0,5}|\.\d{0,2})$/;
document.getElementById('er').innerHTML = re.test(v);
}
</script>
You'll need separate validation for the final value, e.g.
/^\d{5}\.\d{2}$/.test(value);
to make sure it's the required format.
I don't understand the requirement to add a leading zero to "." since the user must enter 5 leading digits anyway (unless I misunderstand the question).

Javascript switch

I am working on a zodiac calendar that requires a switch 0-11 for the signs. I have written HTML code that drops down for the month and a text input for the year. The sign should use id 'output' and should also show up in text. I am not sure if I am using my switch correctly, of if my math is causing the problem or why it is not sending to output.
HTML CODE:
<div><label for="sign">Sign</label><input type="text"
name ="sign" id="sign"></div>
Javascript Code
if (year && year.value && (year.length == 4)){
year = parseInt(years.value);
month = parseInt(month.value);
if (month < 2) {
year = (year - 1);
}
year = ((year - 1924) % 12);
} else { // Show Error:
document.getElementById('year').value =
'Please enter valid values.';
}
switch (year){
case 0 :
block code;
break;
etc..
} // End Switch
if (output.textContent != undefined) {
output.textContent = sign;
} else {
output.innerText = sign;
}
return false;
}
Your regular expression could be failing to match your lowercased url. When that happens, the result would be null.
You should be checking the match() result before using it. Something like this:
var matches = url.toLowerCase().match(/https?:\/\/(.+?)[?#\/$]/);
if (!matches || matches.length < 2) {
// Handle error
...
} else {
// Keep going
var domain = matches[1];
...
}
Also, verify that your regular expression is actually doing what you intend.
Because of my javascript code innerText
if (output.textContent != undefined) {
output.textContent = sign;
} else {
output.innerText = sign;
}
I had to delete
<div><label for="sign">Sign</label><input type="text"
name ="sign" id="sign"></div>
and replace it with
<p>Sign: <span id="output"></span></p>
I could have easily changed the javascript code and document.getElementID('output') = sign.value;
The problem should be caused by domain checking instead of calculate function.
Remove domain checking and try again (see if it works).
Errors:
1) if (year && year.value && (year.value.length == 4)){
year = parseInt(year.value);
2) main html didn't declare element "output"

JavaScript on IE and Chrome? (It works on Firefox)

function ord(string) {
var str = string + '',
code = str.charCodeAt(0);
if (0xD800 <= code && code <= 0xDBFF) { // High surrogate (could change last hex to 0xDB7F to treat high private surrogates as single characters)
var hi = code;
if (str.length === 1) {
return code; // This is just a high surrogate with no following low surrogate, so we return its value;
// we could also throw an error as it is not a complete character, but someone may want to know }
var low = str.charCodeAt(1);
return ((hi - 0xD800) * 0x400) + (low - 0xDC00) + 0x10000;
}
if (0xDC00 <= code && code <= 0xDFFF) { // Low surrogate return code; // This is just a low surrogate with no preceding high surrogate, so we return its value;
// we could also throw an error as it is not a complete character, but someone may want to know
}
return code;
}
}
$(document).ready(function () {
var maxTxtNumber = 8;
var arrTxtNumber = new Array();
var txtvalues = new Array();
var arr = {};
$('.numericonly').keypress(function (e) {
var t = $(this).val();
var k = e.which;
delete arr[8];
if ((e.which >= 49 && e.which <= 55) || e.which == 8) {
if (e.which == 8) {
var s = new String(t);
s = s.charCodeAt(0);
delete arr[s];
}
if (arr[k]) {
e.preventDefault();
} else {
arr[k] = e.which;
}
} else {
e.preventDefault();
}
});
});
The code works on Firefox but not on IE and Chrome?
Other browsers use e.keyCode to tell you which key was pressed. Cross-browser:
var k = e.keyCode || e.which;
Also make sure you use k rather than repeating e.which every time.
All that code is not required. If you want to test that an input's value is only digits, then something like the following will do:
<input type="text" onblur="check(this);" ...>
function check(el) {
if (!isDigits(el.value)) {
alert('Hey!!\nThe element you just left should only contain digits');
}
}
function isDigits(s) {
return /^\d*$/.test(s);
}
It's much more friendly to give the user a hint about the format you require and wait until they either leave the control or submit the form before offering a warning about invalid values. You really don't care how the user gets to a valid value, just so long as it's valid when the form is submitted.
And you must validate on the server again.
I recommend running your code through a validator such as http://www.jslint.com/ to make sure that everything adheres to universal standards.

Format currency using javascript

a script returns either a number like 0.0580 so in x.xxxx format or a (x) for X units left.
I want to format the number 0.0580 and return 5.8 cent or return x units left.
Any ideas how to do that in javascript? Especially how do I format the x.xxxx?
In case the first x is not 0 I want to return e.g. 1.75$.
MS has written a nice plugin for jquery. it's especially useful if you're localizing. Give it a go:
http://weblogs.asp.net/scottgu/archive/2010/06/10/jquery-globalization-plugin-from-microsoft.aspx
I'm not sure if this can be used outside of jquery...
I may be spoiling you here, but whatever. Here's a function that I found somewhere at some point and have been recycling since. I haven't actually bothered to look much into it to figure out what it does exactly, but it has been rather useful:
function FormatMoneyAmount(starting_string, ending_string) {
//check validity of input (true = invalid, false = valid)
var valid_exp = new RegExp ('[^0-9,.$]', 'gi');
input_invalid = (typeof(ending_string) == 'undefined' && valid_exp.test(starting_string));
//check if more than 2 digits follow decimal or no decimal
decimal_invalid = typeof(ending_string) == 'undefined' && (starting_string.indexOf('.') > -1) && ((starting_string.length - starting_string.indexOf('.')) > 3);
if (input_invalid || decimal_invalid) {
ending_string = starting_string;
} else {
//remove commas, dollar signs
var replace_exp = new RegExp ('[,$]', 'gi');
starting_string = starting_string.replace(replace_exp, '');
//remove decimal if ending string not set, save for adding on later
var decimal_substring = '';
if (typeof(ending_string) == 'undefined' && starting_string.indexOf('.') > -1) {
decimal_substring = starting_string.substring(starting_string.indexOf('.'), starting_string.length);
remaining_string = starting_string.substring(0,starting_string.indexOf('.'));
} else {
remaining_string = starting_string;
}
//if string is already 3 characters or less, do nothing
if (remaining_string.length > 3) {
//separate last 3 characters of string from rest of string
var final_three = remaining_string.substring(remaining_string.length - 3, remaining_string.length);
remaining_string = remaining_string.substring(0, remaining_string.length - 3);
//if not first group of 3, add new group before old group with comma, else set to new group
ending_string = (typeof(ending_string) == 'undefined') ? final_three + ((typeof(decimal_substring) == 'undefined') ? '' : decimal_substring) : final_three + ',' + ending_string;
//call function again if more than 3 digits remaining to process, else add to end string
if (remaining_string.length > 3) {
ending_string = FormatMoneyAmount(remaining_string, ending_string);
} else {
ending_string = remaining_string + ',' + ending_string;
}
} else {
ending_string = (typeof(ending_string) == 'undefined') ? remaining_string : remaining_string + ',' + ending_string + ((typeof(decimal_substring) == 'undefined') ? '' : decimal_substring);
}
}
return ending_string;
}
The first thing to do is check the format of the string, since you will have two code paths depending on the result:
if (typeof num = "string" && num.slice(0,1) == "(" && num.slice(-1) == ")") {
// String is in the format (x), so we just need to return that number
return num.slice(1,-1) + " units left";
}
The next part is to check if the number is less than 1, indicating that it is cents and not whole dollars. If it is less than 1, multiplying it by 100 will give you the number of cents you're after:
if (+num < 1)
// 0.0580 * 100 = 5.8
return (num * 100) + " cents";
else
return +num + "$";

Categories