jquery add dash between characters if length is greater than x - javascript

I am trying to format a US zip code as the user types, and need to add a dash between the 5th and and 6th characters if the user types more than 5 so the the zip code is formatted like
55555 or 55555-5555
what I have now adds a dash, but regardless if a 6th number is added
//zip code formatting
$(".zip-val").keyup(function() {
if($(this).val().length == 5) {
$(this).val($(this).val() + "-");
}
});

How about this?
//zip code formatting
$(".zip-val").keyup(function() {
zipcode = $(this).val();
zipcode = zipcode.replace(/-/g, ''); // remove all occurrences of '-'
if(zipcode.length > 5) {
$(this).val(zipcode.substring(0, 5) + "-" + zipcode.substring(5));
}
});

Could try this, splitting it and keeping the number groups then recreating the string with formats. This even deletes the - if you are not in a group of 5.
You could also modify this to fit into a credit card number system.
//zip code formatting
$(".zip-val").keyup(function() {
let val = $(this).val();
if(val.length > 5) {
let digits = val.split(/(\d{1,5})/);
let str = "";
for (let group of digits)
{
if (/^\d+$/.test(group))
{
str += group + "-";
}
}
str = str.substring(0, str.length - 1);
$(this).val(str);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" class="zip-val" />

you should check if the length is 6 or not. Also, you can add more check, if the users use backspace on the 6th character, it would also delete the '-' character
$(".zip-val").keyup(function(e) {
if(e.keyCode == 8)
{
if($(this).val().length == 6){
var newText = $(this).val().substring(0 , 5);
$(this).val(newText);
}
}
else if($(this).val().length == 6) {
var newText = $(this).val().substring(0 , 5) + '-' + $(this).val().substring(5);
$(this).val(newText);
}
});
demo : https://jsfiddle.net/sn5ghvb8/

You can try this.
$(".zip-val").keyup(function() {
if($(this).val().length > 5 ) {
res = $(this).val().split("");//convert string to array
if(jQuery.inArray( "-", res )){//checks if dash exist
for (var i=res.length-1; i>=0; i--) {//removes dashes
if (res[i] === '-') {
res.splice(i, 1);
}
}
res.splice(5, 0, "-");
}
$(this).val(res.join(''));
}
});

Related

Double Spaces in Javascript

This code should show an alert box if there are no double spaces but it's not doing that.
var str = prompt("Enter Some Text");
var numChars = str.length;
for (var i = 0; i < numChars; i++) {
if (str.slice(i, i + 2) === " ") {
alert("No double spaces!");
break;
}
}
alert will pop out if no double spaces
You could make this a little simpler with an indexOf check:
var str = prompt("Enter Some Text");
if (str.indexOf(" ") === -1) {
alert("No double spaces!");
}
a simple regular expression can do it :
const str = prompt("Enter Some Text");
!/\s\s/.test(str) && alert('No double spaces found !');
If you want to keep that with the for approach, you should invert the logic and check whether the double whitespace occurs:
var str = prompt("Enter Some Text");
var numChars = str.length;
var doubleWhitespace = false;
for (var i = 0; i < numChars; i++) {
// get the current and next character.
var [curr, next] = [str[i], str[i + 1]];
// if both exists and current is the same as next and both the characters are spaces
if (curr && next && curr === next && curr === ' ') {
// double white space.
doubleWhitespace = true;
break;
}
}
if (doubleWhitespace) alert('There is a double space!');
else alert('NO double space');
However, there is a slightly easier solution by just using indexOf:
var str = prompt("Enter Some Text");
if (str.indexOf(' ') > -1) alert("There are double spaces!");
else alert("There are no double spaces!");
you need change this line
if (str.slice(i, i + 2) === " ") {
with
if (str.slice(i, i + 2) === " ") {

Check if string is valid SSN as its being typed using Javascript

I want to do a validate check to see if the SSN entered into a textbox follows this specific format: XXX-XX-XXXX as its being typed
I tried doing a function that just auto formats like this...
function ssnCheck() {
var val = this.value.replace(/\D/g, '');
var newVal = '';
if(val.length > 4) {
this.value = val;
}
if((val.length > 3) && (val.length < 6)) {
newVal += val.substr(0, 3) + '-';
val = val.substr(3);
}
if (val.length > 5) {
newVal += val.substr(0, 3) + '-';
newVal += val.substr(3, 2) + '-';
val = val.substr(5);
}
newVal += val;
this.value = newVal;
}
But it would bug out sometimes and not fully work especially on Mobile devices. I tried the solutions below, but they aren't working. The way I'm applying the above is by doing this..
document.getElementById("ssn").addEventListener('keyup',ssnCheck,false);
Any help on getting it to work so it auto formats as its being typed, or a better solution to this issue since it HAS to show in the XXX-XX-XXXX format when they are done typing in the box.
try this regax:
^\d{3}(?:[-]\d{2})(?:[-]\d{4})?$
^ = Start of the string.
(?:…) = Grouping
\d{3} = Match 3 digits
\d{2} = Match 2 digits
\d{4} = Match 4 digits
[-] = Match a hyphen
$ = End of the string

How do I check if an input contains an isbn using javascript

I need a script that will test an input field's contents to see if it contains an ISBN. I found a few examples of this, but none of them strip the dashes. I need this to happen or my search results don't work. I have the else part of the script working if the field doesn't have an ISBN, but can't get the ISBN test to work. Thank you in advance for any help!
function search() {
var textboxdata = $('#search').val();
if (textboxdata contains an ISBN number, strip it of dashes and) {
// perform ISBN search
document.location.href = "http://myurl?search=" + textboxdata;
}
else { //perform other search
}
}
Based on the algorithms given in the Wikipedia article, here's a simple javascript function for validating 10- and 13-digit ISBNs:
var isValidIsbn = function(str) {
var sum,
weight,
digit,
check,
i;
str = str.replace(/[^0-9X]/gi, '');
if (str.length != 10 && str.length != 13) {
return false;
}
if (str.length == 13) {
sum = 0;
for (i = 0; i < 12; i++) {
digit = parseInt(str[i]);
if (i % 2 == 1) {
sum += 3*digit;
} else {
sum += digit;
}
}
check = (10 - (sum % 10)) % 10;
return (check == str[str.length-1]);
}
if (str.length == 10) {
weight = 10;
sum = 0;
for (i = 0; i < 9; i++) {
digit = parseInt(str[i]);
sum += weight*digit;
weight--;
}
check = (11 - (sum % 11)) % 11
if (check == 10) {
check = 'X';
}
return (check == str[str.length-1].toUpperCase());
}
}
There is also a js library available for checking ISBN10 and ISBN13 formatting: isbnjs as well as isbn-verify
Edit 2/2/17 - previous link was to Google Code, some updated current links:
- npm for isbn-verify
- npm for isbnjs
- Github project
Take a look at this Wikipedia article:
http://en.wikipedia.org/wiki/International_Standard_Book_Number
Should give you some insight into how to validate an ISBN number.
Derek's code fails for this ISBN ==> "0756603390"
It's because the check digit will end up as 11.
incorrect == > check = 11 - (sum % 11);
correct ==> check = (11 - (sum % 11)) %11;
I tested the new code against 500 ISBN10s.

Format number string using commas

I want to format numbers. I have seen some of the regex expression example to insert comma in number string. All of them check 3 digits in a row and then insert comma in number. But i want something like this:
122 as 122
1234 as 1,234
12345 as 12,345
1723456 as 17,23,456
7123456789.56742 as 7,12,34,56,789.56742
I am very new to regex expression. Please help me how to display the number as the above. I have tried the below method. This always checks for 3 digits and then add comma.
function numberWithCommas(x) {
return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}
But i want comma every 2 digits except for the last 3 digits before the decimals as shown above.
The result will depend on your browsers locale. But this might be an acceptable solution:
(7123456789.56742).toLocaleString();
Outputs:
7,123,456,789.56742
Try it and see if it outputs 7,12,34,56,789.567421 in your locale.
Here's a function to convert a number to a european (1.000,00 - default) or USA (1,000.00) style:
function sep1000(somenum,usa){
var dec = String(somenum).split(/[.,]/)
,sep = usa ? ',' : '.'
,decsep = usa ? '.' : ',';
return dec[0]
.split('')
.reverse()
.reduce(function(prev,now,i){
return i%3 === 0 ? prev+sep+now : prev+now;}
)
.split('')
.reverse()
.join('') +
(dec[1] ? decsep+dec[1] :'')
;
}
Alternative:
function sep1000(somenum,usa){
var dec = String(somenum).split(/[.,]/)
,sep = usa ? ',' : '.'
,decsep = usa ? '.' : ',';
return xsep(dec[0],sep) + (dec[1] ? decsep+dec[1] :'');
function xsep(num,sep) {
var n = String(num).split('')
,i = -3;
while (n.length + i > 0) {
n.splice(i, 0, sep);
i -= 4;
}
return n.join('');
}
}
//usage for both functions
alert(sep1000(10002343123.034)); //=> 10.002.343.123,034
alert(sep1000(10002343123.034,true)); //=> 10,002,343,123.034
[edit based on comment] If you want to separate by 100, simply change i -= 4; to i -= 3;
function sep100(somenum,usa){
var dec = String(somenum).split(/[.,]/)
,sep = usa ? ',' : '.'
,decsep = usa ? '.' : ',';
return xsep(dec[0],sep) + (dec[1] ? decsep+dec[1] :'');
function xsep(num,sep) {
var n = String(num).split('')
,i = -3;
while (n.length + i > 0) {
n.splice(i, 0, sep);
i -= 3; //<== here
}
return n.join('');
}
}
use toLocaleString();
It automatically handles inserting commas and will also handle uk strings the right way
e.g.
var num=63613612837131;
alert(num.toLocaleString());
Below is the snippet of code, can be done in better way but this works :D
function formatDollar(num)
{
var p = num.toFixed(2).split(".");
var chars = p[0].split("").reverse();
var sep1000 = false;
var newstr = '';
var count = 0;
var count2=0;
for (x in chars)
{
count++;
if(count%3 == 1 && count != 1 %% !sep1000)
{
newstr = chars[x] + ',' + newstr;
sep1000=true;
}
else
{
if(!sep1000)
{
newstr = chars[x] + ',' + newstr;
}
else
{
count2++;
if(count%2 == 0 && count != 1)
{
newstr = chars[x] + ',' + newstr;
}
else
{
newstr = chars[x] + newstr;
}
}
}
}
return newstr + "." + p[1];
}

Reformat string containing uk postcode using regex

How can I format a string using Javascript to match a regex?
I am using UK postcodes which could match any of the following
N1 3LD
EC1A 3AD
GU34 8RR
I have the following regex which validates a string correctly, but I am unsure how to use the regex as a mask to format EC1A3AD to EC1A 3AD / GU348RR to GU34 8RR / N13LD to N1 3LD.
My regex is /^[A-Za-z]{1,2}[0-9A-Za-z]{1,2}[ ]?[0-9]{0,1}[A-Za-z]{2}$/
Thank you
If you use the regular expression /^([A-Z]{1,2}\d{1,2}[A-Z]?)\s*(\d[A-Z]{2})$/ you can extract the two parts of the postcode and reassemble them with an intervening space.
var list = ['N13LD', 'EC1A3AD', 'GU348RR'];
for (var i = 0; i < list.length; i++) {
var parts = list[i].match(/^([A-Z]{1,2}\d{1,2}[A-Z]?)\s*(\d[A-Z]{2})$/);
parts.shift();
alert(parts.join(' '));
}
output
N1 3LD
EC1A 3AD
GU34 8RR
Put braces around the bits separated by the optional space:
/^([A-Za-z]{1,2}[0-9A-Za-z]{1,2})[ ]?([0-9]{0,1}[A-Za-z]{2})$/
However I think the regexp is wrong... The above regexp splits "N13LD" as "N13", "LD".
I suspect the errant part is the {0,1} before the two trailing letters - there must AFAIK be exactly one digit there:
var re = /^([A-Z]{1,2}[\dA-Z]{1,2})[ ]?(\d[A-Z]{2})$/i; // case insensitive
The grouping allows the string.match(regexp) function to return a result which includes an entry for each matching group:
> "N13LD".match(re);
["N13LD", "N1", "3LD"]
> "GU348RR".match(re);
["GU348RR", "GU34", "8RR"]
> "EC1A3AD".match(re);
["EC1A3AD", "EC1A", "3AD"]
To get your result, just use trivial string concatenation to join the 2nd and 3rd element from each result together.
I've used the excellent answer from #borodin above to create a UK postcode as-you-type formatter. Note, this does not validate the postcode, just formats it according to borodin's regex as the user types.
var txtPc = $("#postcode");
var outputCount = 0;
var jigCount = 0;
var postcodePauseTime = 500;
txtPc.on("keydown", function(e) {
var keyCode = e.which;
var key = String.fromCharCode(keyCode);
var isAlphaNumeric = //key.match(/^[a-z0-9]+$/i);
(
(keyCode >= 65 && keyCode <= 90) ||
(keyCode >= 48 && keyCode <= 57) ||
([189, 190, 8, 46, 9].indexOf(keyCode) > -1) ||
(keyCode >= 35 && keyCode <= 40)
);
return !!isAlphaNumeric;
});
// handle click and add class
txtPc.on("keyup", function(e) {
PostcodeCalculateFormat(txtPc);
});
txtPc.on("blur", function() {
PostcodeCalculateFormat(txtPc);
});
function PostcodeCalculateFormat(txtPc) {
(function(index, txtPc) {
setTimeout(function() {
//prevent interferance from other keypresses by returning out of this closure
if (index != jigCount) return;
var isFocused = ($('#' + txtPc.attr('id') + ':focus')[0] == document.activeElement);
var postcodeText = txtPc.val().toUpperCase(); /// + key;
var origSpacePos = postcodeText.indexOf(" ");
postcodeText = postcodeText.replace(/[\W_]+/g, "");
var parts = postcodeText.match(/^([A-Z]{1,2}\d{1,2}[A-Z]?)\s*(\d[A-Z]{2})$/i);
//if unable to match the lot, try the first part only with less strict reg
if (!parts)
parts = postcodeText.match(/^([A-Z]{1,2}\d{1,2}[A-Z]?)\s*(.*)$/i);
if (parts) {
var caretPos = 0;
if (isFocused)
caretPos = getCaretPosition(txtPc[0]).start;
parts.shift();
var newVal = parts.join(' ');
if (newVal == txtPc.val())
return;
output(newVal);
txtPc.val(newVal);
var spacePos = newVal.indexOf(" ");
if (isFocused) {
if (caretPos >= spacePos && origSpacePos == -1)
caretPos++;
setCaretPosition(txtPc[0], caretPos, caretPos);
}
}
}, postcodePauseTime);
}(++jigCount, txtPc));
}
function output(str) {
$("#listOutput").prepend("<li>[" + (++outputCount) + "] " + str + "</li>");
}
function getCaretPosition(ctrl) {
// IE < 9 Support
if (document.selection) {
ctrl.focus();
var range = document.selection.createRange();
var rangelen = range.text.length;
range.moveStart('character', -ctrl.value.length);
var start = range.text.length - rangelen;
return {
'start': start,
'end': start + rangelen
};
}
// IE >=9 and other browsers
else if (ctrl.selectionStart || ctrl.selectionStart == '0') {
return {
'start': ctrl.selectionStart,
'end': ctrl.selectionEnd
};
} else {
return {
'start': 0,
'end': 0
};
}
}
function setCaretPosition(ctrl, start, end) {
// IE >= 9 and other browsers
if (ctrl.setSelectionRange) {
ctrl.focus();
ctrl.setSelectionRange(start, end);
}
// IE < 9
else if (ctrl.createTextRange) {
var range = ctrl.createTextRange();
range.collapse(true);
range.moveEnd('character', end);
range.moveStart('character', start);
range.select();
}
}
body {
background: silver;
padding: 20px;
font-family: Helvetica;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<div>Sample postcodes to type: 'BT92PE', 'EC1A3AD', 'GU348RR', 'N13LD'</div>
<div>
Postcode: <input id="postcode" style="text-transform: uppercase; " />
</div>
<!-- for troubleshooting -->
<ul id="listOutput"></ul>
The caret get & set functions were taken straight from a stack overflow answer, which I can't find right now to give the user credit. I will look & update with a link if I can.
This does everything I want it to, but it's not a very elegant solution. I'm happy for somebody out there to revamp, enhance or improve on this. I'd like to see the result.
Improvement for future: if the caret is after the space, the backspace key should remove the space AND the alphanumeric character before it in one key press. (same idea for the delete button if the caret is in before the space.)

Categories

Resources