I'm using the following JavaScript + Regex to auto add commas to a user input as they type:
$('input.number').keyup(function(event) {
// skip for arrow keys
if(event.which >= 37 && event.which <= 40) return;
// format number
$(this).val(function(index, value) {
return value
.replace(/[^-\d.]/g, "")
.replace(/\B(?=(\d{3})+(?!\d))/g, ",")
;
});
});
This works great, but it does not work for decimals. It adds commas to the decimals, which I don't want.
I could update the code to do a check to see if there are commas after the decimal. However, I think there may be a more elegant solution with Regex.
$('input.number').keyup(function(event) {
// skip for arrow keys
if(event.which >= 37 && event.which <= 40) return;
// format number
$(this).val(function(index, value) {
var num = value
.replace(/[^-\d.]/g, "")
.replace(/\B(?=(\d{3})+(?!\d))/g, ",");
var numSplit = num.split('.');
if(numSplit.length > 1){
num = numSplit[0] + '.' + numSplit[1].replace(/,/g, "");
}
return num;
});
});
I've tried adding a check to first see if a . exists. But I did not write it correctly.
\B(?=[^.](\d{3})+(?!\d))
Is there a better way to do this with regex?
https://codepen.io/anon/pen/gNOgMm
Apply Regex only to the whole number
$('input.number').keyup(function(event) {
// skip for arrow keys
if (event.which >= 37 && event.which <= 40) return;
// format number
$(this).val(function(index, value) {
var num = value
.replace(/[^-\d.]/g, "")
var numSplit = num.split('.');
if (numSplit.length > 1) {
num = numSplit[0]
.replace(/\B(?=(\d{3})+(?!\d))/g, ",") + '.' + numSplit[1].replace(/,/, "");
} else {
num = num.replace(/\B(?=(\d{3})+(?!\d))/g, ",")
}
return num;
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<input class="number">
Shorter Version
$('input.number').keyup(function(event) {
// skip for arrow keys
if (event.which >= 37 && event.which <= 40) return;
// format number
$(this).val(function(index, value) {
var num = value
.replace(/[^-\d.]/g, "")
.replace(/^\.+/g, "")
.replace(/\./, "x").replace(/\./g, "").replace(/x/, ".")
return (/^\d+\.\d+$/.test(num))
? num.replace(/(\d)(?=(\d{3})+(?:\.\d+)$)/g, "$1,")
: num.replace(/\B(?=(\d{3})+(?!\d))/g, ",")
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<input class="number">
So, with a simple replace callback you can match the decimal part
then just return it, or match the assertion for a thousands place
then return ,.
No need to split, it just makes it more complicated.
Since you're using regex, do it all with regex.
The regex expanded:
( \. \d* ) # (1), Decimal part
| # or,
\B # Thousands part
(?=
(?: \d{3} )+
(?! \d )
)
var input = "122341234.188874";
input = input.replace (/[^-\d.]/g, "" );
input = input.replace (/(\.\d*)|\B(?=(?:\d{3})+(?!\d))/g,
function( m, g1 ) // match, group 1
{
if ( g1 > "" )
return g1;
else
return ",";
}
);
console.log(input);
Another thing you may want to consider is to validate the
form after stripping invalid characters.
I believe you could do that with a
replace (/^(?:.*?(-?(?:\d+(?:\.\d*)?|\.\d+))|).*$/g, "$1" );
I noticed when I literally type the word test or dabd, it fails by saying "test is a palindrome"; obviously these should fail. I test other words like racecar, madam, cat, they all pass. I check from the left most character and right most character and go down until we reach the middle. What could be the issue?
function lengthChecker() {
var str = document.getElementById("str").value;
if (str.length > 10) {
alert("Sorry. Your input surpasses the 10 characters maximum. Please try again.")
return false;
} else if (str.length == 0) {
alert("Sorry. Your input is too short, and doesn't meet the 10 characters maximum. Please try again.")
return false;
}
palindrome(str);
}
function palindrome(str) {
var j = str.length;
if (/\s/.test(str)) {
alert("No spaces allowed.")
return false;
}
for (i = 0; i < j / 2; i++) {
if (str[i] == str[j - 1 - i]) {
isPalindrome('', str);
return true;
} else {
notPalindrome(str);
return false;
}
}
}
function isPalindrome(e, str) {
alert(str + " is a Palindrome.");
}
function notPalindrome(str) {
alert(str + " isn't a Palindrome");
}
document.addEventListener("DOMContentLoaded", function(e) {
var el = document.getElementById("checkInput");
el.addEventListener("click", lengthChecker);
});
In palindrome() you always only check the first character and immediately return. Fix the loop like this:
for (var i = 0; i < j / 2; i++) {
if (str[i] != str[j - 1 - i]) {
notPalindrome(str);
return false;
}
}
isPalindrome('', str);
return true;
For reference, you don't need to loop. You can simplify the palindrome test to just this:
str === str.split('').reverse().join('')
This splits the string into an array, which can then be reversed. It then joins it back into a string so you can compare it.
I'd then put this in a ternary statement for modifying the message:
var notp = (str === '' || str !== str.split('').reverse().join('').replace(" ", "")) ? 'is NOT':'IS';
I added "str === ''" to test for non-entries, and I added a remove spaces test as well. Now you've got a variable that you can push into a generic alert or whatever. You can change that to read "true:false;" instead is you want to control more than just the text of the message.
The following gets rid of the leading and trailing spaces:
str = str.trim();
There are more edits you can make, but this should help you along. Here's a jsfiddle:
https://jsfiddle.net/mckinleymedia/fudLdx0r/
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
In a web application, how do I determine whether the first letter in a given string is upper- or lower-case using JavaScript?
You can use toUpperCase:
if(yourString.charAt(0) === yourString.charAt(0).toUpperCase()) {
//Uppercase!
}
If you're going to be using this on a regular basis, I would suggest putting it in a function on the String prototype, something like this:
String.prototype.isFirstCapital = function() {
return this.charAt(0) === this.charAt(0).toUpperCase();
}
if(yourString.isFirstCapital()) {
//Uppercase!
}
Update (based on comments)
I don't know what you actually want to do in the case that the string does not being with a letter, but a simple solution would be to add a quick check to see if it does or not, and return false if not:
String.prototype.isFirstCapital = function() {
return /^[a-z]/i.test(this) && this.charAt(0) === this.charAt(0).toUpperCase();
}
This will work only with English alphabet.
var ch = myStr.chatAt(0);
if (ch >= 'a' && ch <= 'z') {
// small
} else if (ch >= 'A' && ch <= 'Z') {
// capital
} else {
// not english alphabet char
}
var mystring = "Test string";
var first= "";
if (mystring )
{
first= mystring[1];
}
if (first)
{
$('p').each(function()
{
if ($(this).text().charAt(0).toUpperCase() === $(this).text().charAt(0))
{
alert("Uppercase");
}
});
}
This will be called recursively until a first letter in a string is approached, otherwise returns 'no letters'.
function getFirstCase(string) {
if (string === '') return 'no letters';
var firstChar = string.charAt(0);
/*
* If both lowercase and uppercase
* are equal, it is not a letter
*/
if (firstChar.toLowerCase() === firstChar.toUpperCase()) {
return getFirstCase(string.substr(1));
} else {
return firstChar.toLowerCase() === firstChar ? 'lowercase' : 'uppercase';
}
}
Testing:
console.log(getFirstCase('alphabet'),
getFirstCase('Sunshine'),
getFirstCase('123123'),
getFirstCase('#Hi'),
getFirstCase('\nHAHA'));
I'm surprised no one's offered a regex solution to this - it seems like the easiest by far:
function getFirstCase(s) {
return (/^[\d\W]*[A-Z]/).test(s) ? 'upper' :
(/^[\d\W]*[a-z]/).test(s) ? 'lower' :
'none';
}
Blatantly stealing #Lapple's test cases:
console.log(getFirstCase('alphabet'),
getFirstCase('Sunshine'),
getFirstCase('123123'),
getFirstCase('#Hi'),
getFirstCase('\nHAHA'));
// lower upper none upper upper
See http://jsfiddle.net/nrabinowitz/a5cQa/
I am trying to get this Javascript in my application working.
function validateQuantity(field)
{
var value = field.value; //get characters
//check that all characters are digits, ., -, or ""
for(var i=0; i < field.value.length; ++i)
{
var new_key = value.charAt(i); //cycle through characters
if(((new_key <= "0") || (new_key > "9")) &&
!(new_key == ""))
{
alert("Please enter number and greater than 0 only");
return false;
break;
}
return true;
}
}
And I have a input button as below
<input class="buttonToLink" type="submit" value="Update"
onclick="return validateQuantity(document.getElementById('quantity'))"/>
The above code successfully checks the input of all alphabet such as "abc" or alphabet and numeric such as "abcd123" as false.
However, when I put numeric characters first, along with alphabet such as "123abc", it fails -- it does not show the alert.
What did I do wrong with the code, and how can it be fixed?
function validateQuantity(field) {
if (!/^\d+$/.test(field.value)) { // is an integer
alert("Please enter number and greater than 0 only");
return false;
}
return true;
}
The reason your code doesn't work is because you have the return true statement inside the loop. As soon as it sees a valid integer it will return true and break out of the function, ignoring anything that comes after it. Allowing strings like "123abc" for example.
This is probably what you wanted:
function validateQuantity(field)
{
var value = field.value; //get characters
//check that all characters are digits, ., -, or ""
for(var i=0; i < field.value.length; ++i)
{
var new_key = value.charAt(i); //cycle through characters
if(((new_key <= "0") || (new_key > "9")) &&
!(new_key == ""))
{
alert("Please enter number and greater than 0 only");
return false;
break;
}
}
return true;
}
if (parseInt(new_Key) == new_Key) {
//valid
} else { // it will return NaN
//invalid
}
Try parsing the value as an integer, and compare with the original value.
var isAllNumbers = (parseInt(field.value) == field.value);
Perhaps use a jQuery selector, and use a regex to test for numeric.
var isAllNumbers = $("#quantity").val().match(/\d+$/);