What regex would match this starting from 0.5 to 24 - javascript

I want a regex that would match this range: 0.5 - 24, but not this: 0,5 or 22,5. For now I have this one:
/^(([0-9]|1[0-9]|2[0-3])([^,])(\.(0|5)))$/
but for some reason it matches this 22,5 even though I negated the ,. Thanks!

You just need to only allow the dot and make a last capture group optional.
Like this:
/^([0-9]|1[0-9]|2[0-3])(\.[05])?$/
(\.[05])? <- this allows, by the ? symbol, one or zero ocurrences of the second capture group.

In terms of regular expressions, this will suit your needs.
^((0\.[5-9])|(([1-9](\.[5-9])?)|(1[0-9](\.[5-9])?)|(2[0-3](\.[5-9])?)|24))$
You can test it here
However, if what you want is to check a range, I would advise you to use regular expressions just to check if the number is valid, and then, convert it and use plain javascript for your validation.
var validator = function(value) {
var regexp = /^-?\d+(\.\d{0,2})?$/;
var isNumber = regexp.test(value);
if (isNumber) {
var parsed = parseFloat(value);
if (0.5 <= parsed && parsed <= 24)
console.log("The number " + parsed + " is within range");
else
console.log("The number " + parsed + " is NOT within range");
} else {
console.log("The value " + value + " is NOT even a valid decimal value");
}
}
validator("-3");
validator("19.6");
validator("22,5");

Related

make a regex to validate a string with only one number

here my probleme, in some project i need to validate a string, it must be a length of 4 character and contains one and only one number but i don't know it's place (can be "er1t" or "4frt" but not "sdfd" or "4fd5")
i have made a regex which work : (?:[a-z]\d[a-z]{2}|\d[a-z]{3}|[a-z]{2}\d[a-z]|[a-z]{3}\d) but it's not optimised and I don't find how i search for a number in a string in regex, i use a javascript regex.
Thank in advance,
ekanS
Looks like you can use
^(?=[a-z]*\d[a-z]*$)[a-z\d]{4}$
Demo.
In short, we can set a (?=\D*\d\D*$) condition to check if the whole line/string has only 1 number at the very start of a line/string. Then we can allow any lowercase letters and numbers.
If you plan to allow upper case letters, add A-Z to the character class, or use i option.
function isValid(code) {
var re = /^(?=[a-z]*\d[a-z]*$)[a-z\d]{4}$/gm;
if ((m = re.exec(code)) !== null) {
document.getElementById("res").innerHTML = document.getElementById("res").innerHTML + "<br>" + m[0] + " is <font color=\"#0000FF\">valid</font>.";
}
else {
document.getElementById("res").innerHTML = document.getElementById("res").innerHTML + "<br>" + code + " is <font color=\"#FF0000\">not valid</font>.";
}
}
isValid('er1t');
isValid('4frt');
isValid('sdfd');
isValid('4fd5');
isValid('ffd5');
document.getElementById("res").innerHTML + "</font>"
<div id="res"><font face="Arial"><b>Valid codes:</b><font face="Tahoma"><div>

validate amount field using javascript

i been looking everywhere for a solution but nothing which quiet matches my criteria.
i want to enable the user to input any positive numbers with (optional 2 decimal places separated by a dot '.')
i.e: 1.23, 12.23, 123.23, 1234.23, 1, 0
how can i do this?
i attempted to use this regex
$('form').submit(function(){
var amount = $('#amount');
var regex = new RegExp("^\d+(\.\d{1,2})?$");
var error = 0;
if(amount.val() == '' || amount.val() <= 0 || regex.test(amount.val()) == false){
$('label', amount.parent()).addClass('error');
error++;
}else{
$('label', amount.parent()).removeClass('error');
}
if(error > 0){
return false;
}
});
i am not very experienced with regex, and attempted to use the code above which i found through my search but it doesn't seem to work and i don't know why. i am not sure if it is an error in the regex or the way i am using it.
Use var regex = new RegExp("^[-+]?\d+(\.\d\d?)?$"); for 2 decimal places(1st compulsory, 2nd not).
Something like:
^\d+(\.\d{1,2})?$
Note we dropped the sign part [-+]? because you stated only positive numbers.
Explanation:
^ start of string
\d+ match zero or more digits
(\.\d{0,2})? match the pattern in the brackets 0 or 1 time
\. match a literal .
\d{1,2) match 1 or 2 digits
$ end of string
So this allows some digits optionally followed by a . and 1 or 2 more digits. Adjust as needed.
var rx = /^\d+(\.\d{1,2})?$/;
alert(rx.test("1.22") + "\n" // true
+ rx.test("10") + "\n" // true
+ rx.test("2223.4") + "\n" // true
+ rx.test("foo") + "\n" // false
+ rx.test("1..22") + "\n" // false
+ rx.test(" 1")); // false
The regex you've posted allows any number of decimal places. This one only allows 2 decimal places
var regex = new RegExp("^[-+]?\d+(\.\d\d?)?$");
It's long and ugly and I don't remember where I initially got it but this is the one I use (it validates proper comma separation as well, and allows for optional $ at the beginning):
var regex = /^\$?(([1-9][0-9]{0,2}(,[0-9]{3})*)|[0-9]+)?(.[0-9]{2})?$/;
Here's a working fiddle: http://jsfiddle.net/5v9zcxrm/5/
For the decimal places I use (.[0-9]{2}) to only validate 2 decimal places or zero. if you want to allow one decimal place use:
var regex = /^\$?(([1-9][0-9]{0,2}(,[0-9]{3})*)|[0-9]+)?(.[0-9]{1,2})?$/;
If all you need is numbers (with no commas) and a possible decimal of one or two digits use:
var regex = /^\d+(.[0-9]{1,2})?$/;
$('form').submit(function(){
var amount = $('#amount');
var regex = /^\d+(\.\d{2,2})?$/;
var error = 0;
if(amount.val() == '' || amount.val() <= 0 || regex.test(amount.val()) == false){
$('label', amount.parent()).addClass('error');
error++;
}else{
$('label', amount.parent()).removeClass('error');
}
if(error > 0){
return false;
}
});
this is my updated solution which works as intended. special thanks to Matt Burland and everyone who made this possible

filter out a percentage from a string using a regular expression in javascript

I have the following string value: £-155 (-2.2%)
Out of that I want to be able to extract anything that is a number and may/may not contain a '-' minus sign. so the above would be: -2.2
I also need to know whether the value has a percentage in the form as above or not...a conditional statement will be used in the final code.
thoughts?
Why use regex for something so simple? Why not just grab the last character in the string and check if it's a digit or a %.
Likewise, if you want to remove it, just drop the last character from the string using the .substr() method:
http://www.w3schools.com/jsref/jsref_substr.asp
You basically want a regex that matches a number, which has been answered many times before.
Then once you have that, just add an optional percent symbol (%?) and check for its presence in the matched string.
// An optional sign and either an integer followed by an optional fraction
// or a decimal fraction.
var numberRe = '[+-]?(?:[0-9]+(?:[.][0-9]*)?|[.][0-9]+)';
// Matches a number (in group 1)
// and an optional percentage in parentheses (in group 2).
var quantity = new RegExp(
'(' + numberRe + ')(?:\\s*[(]\\s*(' + numberRe + ')\\s*%\\s*[)])?');
If you match with quantity you should get the number in group 1 and any percentage in group 2.
JSON.stringify(quantity.exec('£-155 (-2.2%)'))
["-155 (-2.2%)", "-155", "-2.2"]
To get them as numbers, use parseFloat or unary + as in
var match = quantity.exec('£-155 (-2.2%)');
var n = +match[1], pct = match[2] != null ? +match[2] / 100 : NaN;
alert('n = ' + n + ', whole = ' + (pct ? n / pct : "unknown"));

Regular Expression to reformat a US phone number in Javascript

I'm looking to reformat (replace, not validate - there are many references for validating) a phone number for display in Javascript. Here's an example of some of the data:
123 4567890
(123) 456-7890
(123)456-7890
123 456 7890
123.456.7890
(blank/null)
1234567890
Is there an easy way to use a regular expression to do this? I'm looking for the best way to do this. Is there a better way?
I want to reformat the number to the following: (123) 456-7890
Assuming you want the format "(123) 456-7890":
function formatPhoneNumber(phoneNumberString) {
var cleaned = ('' + phoneNumberString).replace(/\D/g, '');
var match = cleaned.match(/^(\d{3})(\d{3})(\d{4})$/);
if (match) {
return '(' + match[1] + ') ' + match[2] + '-' + match[3];
}
return null;
}
Here's a version that allows the optional +1 international code:
function formatPhoneNumber(phoneNumberString) {
var cleaned = ('' + phoneNumberString).replace(/\D/g, '');
var match = cleaned.match(/^(1|)?(\d{3})(\d{3})(\d{4})$/);
if (match) {
var intlCode = (match[1] ? '+1 ' : '');
return [intlCode, '(', match[2], ') ', match[3], '-', match[4]].join('');
}
return null;
}
formatPhoneNumber('+12345678900') // => "+1 (234) 567-8900"
formatPhoneNumber('2345678900') // => "(234) 567-8900"
Possible solution:
function normalize(phone) {
//normalize string and remove all unnecessary characters
phone = phone.replace(/[^\d]/g, "");
//check if number length equals to 10
if (phone.length == 10) {
//reformat and return phone number
return phone.replace(/(\d{3})(\d{3})(\d{4})/, "($1) $2-$3");
}
return null;
}
var phone = '(123)4567890';
phone = normalize(phone); //(123) 456-7890
var x = '301.474.4062';
x = x.replace(/\D+/g, '')
.replace(/(\d{3})(\d{3})(\d{4})/, '($1) $2-$3');
alert(x);
This answer borrows from maerics' answer. It differs primarily in that it accepts partially entered phone numbers and formats the parts that have been entered.
phone = value.replace(/\D/g, '');
const match = phone.match(/^(\d{1,3})(\d{0,3})(\d{0,4})$/);
if (match) {
phone = `${match[1]}${match[2] ? ' ' : ''}${match[2]}${match[3] ? '-' : ''}${match[3]}`;
}
return phone
I'm using this function to format US numbers.
function formatUsPhone(phone) {
var phoneTest = new RegExp(/^((\+1)|1)? ?\(?(\d{3})\)?[ .-]?(\d{3})[ .-]?(\d{4})( ?(ext\.? ?|x)(\d*))?$/);
phone = phone.trim();
var results = phoneTest.exec(phone);
if (results !== null && results.length > 8) {
return "(" + results[3] + ") " + results[4] + "-" + results[5] + (typeof results[8] !== "undefined" ? " x" + results[8] : "");
}
else {
return phone;
}
}
It accepts almost all imaginable ways of writing a US phone number. The result is formatted to a standard form of (987) 654-3210 x123
thinking backwards
Take the last digits only (up to 10) ignoring first "1".
function formatUSNumber(entry = '') {
const match = entry
.replace(/\D+/g, '').replace(/^1/, '')
.match(/([^\d]*\d[^\d]*){1,10}$/)[0]
const part1 = match.length > 2 ? `(${match.substring(0,3)})` : match
const part2 = match.length > 3 ? ` ${match.substring(3, 6)}` : ''
const part3 = match.length > 6 ? `-${match.substring(6, 10)}` : ''
return `${part1}${part2}${part3}`
}
example input / output as you type
formatUSNumber('+1333')
// (333)
formatUSNumber('333')
// (333)
formatUSNumber('333444')
// (333) 444
formatUSNumber('3334445555')
// (333) 444-5555
2021
libphonenumber-js
Example
import parsePhoneNumber from 'libphonenumber-js'
const phoneNumber = parsePhoneNumber('+12133734253')
phoneNumber.formatInternational() === '+1 213 373 4253'
phoneNumber.formatNational() === '(213) 373-4253'
phoneNumber.getURI() === 'tel:+12133734253'
Based on David Baucum's answer - here is a version that trys to improve auto-replacement "as you type" for example in a React onChange event handler:
function formatPhoneNumber(phoneNumber) {
const cleanNum = phoneNumber.toString().replace(/\D/g, '');
const match = cleanNum.match(/^(\d{3})(\d{0,3})(\d{0,4})$/);
if (match) {
return '(' + match[1] + ') ' + (match[2] ? match[2] + "-" : "") + match[3];
}
return cleanNum;
}
//...
onChange={e => setPhoneNum(formatPhoneNumber(e.target.value))}
It will insert (###) as soon as there are 3 numbers and then it will keep following the RegEx until it looks like this (###) ###-####
I've extended David Baucum's answer to include support for extensions up to 4 digits in length. It also includes the parentheses requested in the original question. This formatting will work as you type in the field.
phone = phone.replace(/\D/g, '');
const match = phone.match(/^(\d{1,3})(\d{0,3})(\d{0,4})(\d{0,4})$/);
if (match) {
phone = `(${match[1]}${match[2] ? ') ' : ''}${match[2]}${match[3] ? '-' : ''}${match[3]}${match[4] ? ' x' : ''}${match[4]}`;
}
return phone;
Almost all of these have issues when the user tries to backspace over the delimiters, particularly from the middle of the string.
Here's a jquery solution that handles that, and also makes sure the cursor stays in the right place as you edit:
//format text input as phone number (nnn) nnn-nnnn
$('.myPhoneField').on('input', function (e){
var $phoneField = e.target;
var cursorPosition = $phoneField.selectionStart;
var numericString = $phoneField.value.replace(/\D/g, '').substring(0, 10);
// let user backspace over the '-'
if (cursorPosition === 9 && numericString.length > 6) return;
// let user backspace over the ') '
if (cursorPosition === 5 && numericString.length > 3) return;
if (cursorPosition === 4 && numericString.length > 3) return;
var match = numericString.match(/^(\d{1,3})(\d{0,3})(\d{0,4})$/);
if (match) {
var newVal = '(' + match[1];
newVal += match[2] ? ') ' + match[2] : '';
newVal += match[3] ? '-' + match[3] : '';
// to help us put the cursor back in the right place
var delta = newVal.length - Math.min($phoneField.value.length, 14);
$phoneField.value = newVal;
$phoneField.selectionEnd = cursorPosition + delta;
} else {
$phoneField.value = '';
}
})
var numbers = "(123) 456-7890".replace(/[^\d]/g, ""); //This strips all characters that aren't digits
if (numbers.length != 10) //wrong format
//handle error
var phone = "(" + numbers.substr(0, 3) + ") " + numbers.substr(3, 3) + "-" + numbers.substr(6); //Create format with substrings
Here is one that will accept both phone numbers and phone numbers with extensions.
function phoneNumber(tel) {
var toString = String(tel),
phoneNumber = toString.replace(/[^0-9]/g, ""),
countArrayStr = phoneNumber.split(""),
numberVar = countArrayStr.length,
closeStr = countArrayStr.join("");
if (numberVar == 10) {
var phone = closeStr.replace(/(\d{3})(\d{3})(\d{4})/, "$1.$2.$3"); // Change number symbols here for numbers 10 digits in length. Just change the periods to what ever is needed.
} else if (numberVar > 10) {
var howMany = closeStr.length,
subtract = (10 - howMany),
phoneBeginning = closeStr.slice(0, subtract),
phoneExtention = closeStr.slice(subtract),
disX = "x", // Change the extension symbol here
phoneBeginningReplace = phoneBeginning.replace(/(\d{3})(\d{3})(\d{4})/, "$1.$2.$3"), // Change number symbols here for numbers greater than 10 digits in length. Just change the periods and to what ever is needed.
array = [phoneBeginningReplace, disX, phoneExtention],
afterarray = array.splice(1, 0, " "),
phone = array.join("");
} else {
var phone = "invalid number US number";
}
return phone;
}
phoneNumber("1234567891"); // Your phone number here
For all international Phone numbers with country code upto 3 digits, we can change the original answer a little bit as below.
For first match instead of looking for '1' we should look for 1-3 digits.
export const formatPhoneNumber = (phoneNumberString) => {
var cleaned = ('' + phoneNumberString).replace(/\D/g, '');
var match = cleaned.match(/^(\d{1,3}|)?(\d{3})(\d{3})(\d{4})$/);
if (match) {
var intlCode = (match[1] ? `+${match[1]} ` : '');
return [intlCode, '(', match[2], ') ', match[3], '-', match[4]].join('');
}
return null;
}
console.log( formatPhoneNumber('16464765278') )//+1 (646) 476-5278
console.log( formatPhoneNumber('+2549114765278')) //+254 (911) 476-5278
console.log( formatPhoneNumber('929876543210') )//+92 (987) 654-3210
Fulfils my requirement.
For US Phone Numbers
/^\(?(\d{3})\)?[- ]?(\d{3})[- ]?(\d{4})$/
Let’s divide this regular expression in smaller fragments to make is easy to understand.
/^\(?: Means that the phone number may begin with an optional (.
(\d{3}): After the optional ( there must be 3 numeric digits. If the phone number does not have a (, it must start with 3 digits. E.g. (308 or 308.
\)?: Means that the phone number can have an optional ) after first 3 digits.
[- ]?: Next the phone number can have an optional hyphen (-) after ) if present or after first 3 digits.
(\d{3}): Then there must be 3 more numeric digits. E.g (308)-135 or 308-135 or 308135
[- ]?: After the second set of 3 digits the phone number can have another optional hyphen (-). E.g (308)-135- or 308-135- or 308135-
(\d{4})$/: Finally, the phone number must end with four digits. E.g (308)-135-7895 or 308-135-7895 or 308135-7895 or 3081357895.
Reference :
http://www.zparacha.com/phone_number_regex/
You can use this functions to check valid phone numbers and normalize them:
let formatPhone = (dirtyNumber) => {
return dirtyNumber.replace(/\D+/g, '').replace(/(\d{3})(\d{3})(\d{4})/, '($1) $2-$3');
}
let isPhone = (phone) => {
//normalize string and remove all unnecessary characters
phone = phone.replace(/\D+/g, '');
return phone.length == 10? true : false;
}
The solutions above are superior, especially if using Java, and encountering more numbers with more than 10 digits such as the international code prefix or additional extension numbers. This solution is basic (I'm a beginner in the regex world) and designed with US Phone numbers in mind and is only useful for strings with just 10 numbers with perhaps some formatting characters, or perhaps no formatting characters at all (just 10 numbers). As such I would recomend this solution only for semi-automatic applications. I Personally prefer to store numbers as just 10 numbers without formatting characters, but also want to be able to convert or clean phone numbers to the standard format normal people and apps/phones will recognize instantly at will.
I came across this post looking for something I could use with a text cleaner app that has PCRE Regex capabilities (but no java functions). I will post this here for people who could use a simple pure Regex solution that could work in a variety of text editors, cleaners, expanders, or even some clipboard managers. I personally use Sublime and TextSoap. This solution was made for Text Soap as it lives in the menu bar and provides a drop-down menu where you can trigger text manipulation actions on what is selected by the cursor or what's in the clipboard.
My approach is essentially two substitution/search and replace regexes. Each substitution search and replace involves two regexes, one for search and one for replace.
Substitution/ Search & Replace #1
The first substitution/ search & replace strips non-numeric numbers from an otherwise 10-digit number to a 10-digit string.
First Substitution/ Search Regex: \D
This search string matches all characters that is not a digit.
First Substitution/ Replace Regex: "" (nothing, not even a space)
Leave the substitute field completely blank, no white space should exist including spaces. This will result in all matched non-digit characters being deleted. You should have gone in with 10 digits + formatting characters prior this operation and come out with 10 digits sans formatting characters.
Substitution/ Search & Replace #2
The second substitution/search and replace search part of the operation captures groups for area code $1, a capture group for the second set of three numbers $2, and the last capture group for the last set of four numbers $3. The regex for the substitute portion of the operation inserts US phone number formatting in between the captured group of digits.
Second Substitution/ Search Regex: (\d{3})(\d{3})(\d{4})
Second Substitution/ Replace Regex: \($1\) $2\-$3
The backslash \ escapes the special characters (, ) , (<-whitespace), and - since we are inserting them between our captured numbers in capture groups $1, $2, & $3 for US phone number formatting purposes.
In TextSoap I created a custom cleaner that includes the two substitution operation actions, so in practice it feels identical to executing a script. I'm sure this solution could be improved but I expect complexity to go up quite a bit. An improved version of this solution is welcomed as a learning experience if anyone wants to add to this.

Performing Arithmetic on Currency Values in the form of Text using Javascript

I am using JQuery to get the contents of a div, which only contains a price in dollars and I would like to add $99 to it, but its text, so when I do the below it won't work.
$('#price_' + part[0]).text($('#price_' + part[0]).text() + 99);
//Changes the div contents to $10099 - if it the contents was $100 to start with
So the question is how can I add the numeric values?
Thanks all
Edit
Please note some numbers can contain a comma i.e. $1,200
Get numerical substring and cast it to a number:
$('#price_' + part[0]).text("$" + (+($('#price_' + part[0]).text()).substring(1) + 99));
Note the use of the unary + operator to cast the string into a number, and the use of substring to get everything after the 1st ($) character in the string.
UPDATE
Since you mentioned the value can contain a comma, you'll be better off breaking this down a bit and performing a string replace:
var div = $('#price_' + part[0]); // get a ref to the div
// replace occurrences of `$` or `,`, cast to a number and add 99
var amount = +div.text().replace(/[$,]/g, '') + 99;
// set the new text to the div
div.text("$" + amount);
Something like this should work
var str = $(...).text();
var sum = parseInt(str.replace(/\D/g, ""));
$(...).text("$" + (sum + 99))
Use parseInt:
var price = $('#price_' + part[0]);
price.text(parseInt(price.text()) + 99);
You'll have to convert the text to int/float before doing the arithmatic
$('#price_' + part[0]).text( parseInt( $('#price_' + part[0]).text() ) + 99);
parseFloat in place of parseInt if you need/want.

Categories

Resources