How can I determine if a string contains only numbers or a comma?
var x = '99,999,999';
var isMatch = x.match('/[\d|,]/');
The above always returns null.
To be a little more exact:
/^\d{1,3}(?:,\d{3})*$/
Only matches when the number is delimited by a comma after every 3rd digit from the right. (This doesn't account for decimals)
Try this: /^[\d,]+$/ Note that this will not tell you if the number is formatted correctly (i.e. ,99, will be accepted just as 99 or 9,999).
/^(?:\d{1,3}(?:,\d{3})*$|^\d+$)/ while more complex, this regex will test to see if the number is a properly formatted number (it won't accept ,,1,,,1,1111,,1,1,1 only 1,11,111,1,111,1111 etc.)
Related
How can I use regex in javascript to match the phone number and only the phone number in the sample string below? The way I have it written below matches "PHONE=9878906756", I need it to only match "9878906756". I think this should be relatively simple, but I've tried putting negating like characters around "PHONE=" with no luck. I can get the phone number in its own group, but that doesn't help when assigning to the javascript var, which only cares what matches.
REGEX:
/PHONE=([^,]*)/g
DATA:
3={STATE=, SSN=, STREET2=, STREET1=, PHONE=9878906756,
MIDDLENAME=, FIRSTNAME=Dexter, POSTALCODE=, DATEOFBIRTH=19650802,
GENDER=0, CITY=, LASTNAME=Morgan
The way you're doing it is right, you just have to get the value of the capture group rather than the value of the whole match:
var result = str.match(/PHONE=([^,]*)/); // Or result = /PHONE=([^,]*)/.exec(str);
if (result) {
console.log(result[1]); // "9878906756"
}
In the array you get back from match, the first entry is the whole match, and then there are additional entries for each capture group.
You also don't need the g flag.
Just use dataAfterRegex.substring(6) to take out the first 6 characters (i.e.: the PHONE= part).
Try
var str = "3={STATE=, SSN=, STREET2=, STREET1=, PHONE=9878906756, MIDDLENAME=, FIRSTNAME=Dexter, POSTALCODE=, DATEOFBIRTH=19650802, GENDER=0, CITY=, LASTNAME=Morgan";
var ph = str.match(/PHONE\=\d+/)[0].slice(-10);
console.log(ph);
I want to allow only integers and floats (upto 3 decimal places) in a text box, how can I achieve this using javascript?
Valid values are
1234
12.3
12.314
1.11
0.4
Not valid
1.23456
abcd or any other character
Based on the comment that you need to also match ".1" you need to add a conditional with the first part of the regular expression.
var re = /^(\d+)?(?:\.\d{1,3})?$/;
Rough test suite - jSFiddle
You can use a regular expression to do this:
/^\d+(?:\.\d{1,3})?$/
That's the start of the string (^), one or more digits (\d+), optionally followed by a . and between 1 and 3 digits ((?:\.\d{1,3})), then the end of the string ($).
To compare it to the value of an input, you'd do something like this:
var re = /^\d+(?:\.\d{1,3})?$/;
var testValue = document.getElementById('id-of-input').value;
if(re.test(testValue)) {
// matches - input is valid
}
else {
// doesn't match - input is invalid
}
Take a look at this jsFiddle demo.
use regular expression to validate your input field , regular rexpression is as below
^[0-9]+(?:\.[0-9]{1,3})?$
Try this:
var reg=/^[\d]+(?:\.\d{1,3})?$/;
str=10.2305;
str1=123;
alert(reg.test(str));
alert(reg.test(str1));
Check Fiddle http://jsfiddle.net/8mURL/1
I have a number like "7847258998" which I want to print with hundred comma separator in javascript.
The result should be:
7,84,72,58,998
i.e the first three digits from right should be grouped together. Remaining digits grouped in chunks of 2. I tried with following:
"7847258998".replace(/\B(?=(\d{3})+(\d{2})+(?!\d))/g, ",")
But it returns: 7,8,4,72,58998. What is the right expression?
Try this:
"7847258998".replace(/\B(?=(\d{2})*(\d{3})$)/g, ",");
I match the end of the string in the lookahead so that I'm always looking for something sane. Otherwise just about anything matches.
Tested on inputs length 1-10.. Enough to decide that it probably works. Pretty inefficient way to do it though, as for each character you have to parse the rest of the string.
But you did ask for a regular expression that does the job =)
function commafy(num)
{
num = num+"";
var re=/(-?\d+)(\d{3})/
while(re.test(num))
{
num=num.replace(re,"$1,$2")
}
return num;
}
function commafyback(num)
{
var x = num.split(',');
return parseFloat(x.join(""));
}
alert(commafy(7847258998))
You can convert the number to a locale string using the en-IN locale.
(7847258998).toLocaleString("en-IN")
If the value is a string, convert it to a number first:
const value = "7847258998"
Number(value).toLocaleString("en-IN")
Reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toLocaleString
function validateDecimal(number,maxDigits)
{
eval("var stringvar=/^[-+]?([0-9]*\.[0-9]{0,"+maxDigits+"})|([0-9]+)$/");
return stringvar.test(number);
}
I wrote above function to validate decimal numbers. The variable 'maxDigits' uses to specify the number of digits in fractional part and 'number' as the value to be validated. But it returned 'true' when I tried with a numeric value followed by a character for eg: 24y. Can anyone help me to figure out my mistake.
Without going into the regex, I think the problem in your code is that you should escape the special character twice. Since you're putting it all inside a string, a single backslash is escaped by the string parsing.
I think this should work:
eval("var stringvar=/^[-+]?([0-9]*\\.[0-9]{0,"+maxDigits+"})|([0-9]+)$/");
This regular expression would validate a number with maxDigits of decimals:
^[-+]?[0-9]*.[0-9]{10}$. This will validate it to 10 decimal places.
Implementing that into JavaScript would look like:
eval("var stringvar=^[-+]?[0-9]*.[0-9]{" + maxDigits + "}$");, or thereabouts.
I have just tried this one and it worked for me: ^[+-]?[0-9]*(\.[0-9]{0,5})?$.
In my case I made a minor modification, you seem to be matching either a decimal number or else a whole number. In my case, I modified the regular expression to take a whole number with an optional decimal section.
As is, the regular expression will match values like: .222, 23.22222 but not 4d.22222, 33.333333, etc.
var n1 = "4.33254";
var n2 = "4d.55";
eval("var stringvar=/^[+-]?[0-9]*(\\.[0-9]{0,5})?$/");
alert(stringvar.test(n1));
alert(stringvar.test(n2));
Yielded: true and false respectively.
Friends,
I'm new to both Javascript and Regular Expressions and hope you can help!
Within a Javascript function I need to check to see if a comma(,) appears 1 or more times. If it does then there should be one or more numbers either side of it.
e.g.
1,000.00 is ok
1,000,00 is ok
,000.00 is not ok
1,,000.00 is not ok
If these conditions are met I want the comma to be removed so 1,000.00 becomes 1000.00
What I have tried so is:
var x = '1,000.00';
var regex = new RegExp("[0-9]+,[0-9]+", "g");
var y = x.replace(regex,"");
alert(y);
When run the alert shows ".00" Which is not what I was expecting or want!
Thanks in advance for any help provided.
strong text
Edit
strong text
Thanks all for the input so far and the 3 answers given. Unfortunately I don't think I explained my question well enough.
What I am trying to achieve is:
If there is a comma in the text and there are one or more numbers either side of it then remove the comma but leave the rest of the string as is.
If there is a comma in the text and there is not at least one number either side of it then do nothing.
So using my examples from above:
1,000.00 becomes 1000.00
1,000,00 becomes 100000
,000.00 is left as ,000.00
1,,000.00 is left as 1,,000.00
Apologies for the confusion!
Your regex isn't going to be very flexible with higher orders than 1000 and it has a problem with inputs which don't have the comma. More problematically you're also matching and replacing the part of the data you're interested in!
Better to have a regex which matches the forms which are a problem and remove them.
The following matches (in order) commas at the beginning of the input, at the end of the input, preceded by a number of non digits, or followed by a number of non digits.
var y = x.replace(/^,|,$|[^0-9]+,|,[^0-9]+/g,'');
As an aside, all of this is much easier if you happen to be able to do lookbehind but almost every JS implementation doesn't.
Edit based on question update:
Ok, I won't attempt to understand why your rules are as they are, but the regex gets simpler to solve it:
var y = x.replace(/(\d),(\d)/g, '$1$2');
I would use something like the following:
^[0-9]{1,3}(,[0-9]{3})*(\.[0-9]+)$
[0-9]{1,3}: 1 to 3 digits
(,[0-9]{3})*: [Optional] More digit triplets seperated by a comma
(\.[0-9]+): [Optional] Dot + more digits
If this regex matches, you know that your number is valid. Just replace all commas with the empty string afterwards.
It seems to me you have three error conditions
",1000"
"1000,"
"1,,000"
If any one of these is true then you should reject the field, If they are all false then you can strip the commas in the normal way and move on. This can be a simple alternation:
^,|,,|,$
I would just remove anything except digits and the decimal separator ([^0-9.]) and send the output through parseFloat():
var y = parseFloat(x.replace(/[^0-9.]+/g, ""));
// invalid cases:
// - standalone comma at the beginning of the string
// - comma next to another comma
// - standalone comma at the end of the string
var i,
inputs = ['1,000.00', '1,000,00', ',000.00', '1,,000.00'],
invalid_cases = /(^,)|(,,)|(,$)/;
for (i = 0; i < inputs.length; i++) {
if (inputs[i].match(invalid_cases) === null) {
// wipe out everything but decimal and dot
inputs[i] = inputs[i].replace(/[^\d.]+/g, '');
}
}
console.log(inputs); // ["1000.00", "100000", ",000.00", "1,,000.00"]