Javascript Regular Expressions - Replace non-numeric characters - javascript

This works:
var.replace(/[^0-9]+/g, '');
That simple snippet will replace anything that is not a number with nothing.
But decimals are real too. So, I'm trying to figure out how to include a period.
I'm sure it's really simple, but my tests aren't working.

Simply: var.replace(/[^\d.-]+/g, '');

Replacing something that is not a number is a little trickier than replacing something that is a number.
Those suggesting to simply add the dot, are ignoring the fact that . is also used as a period, so:
This is a test. 0.9, 1, 2, 3 will become .0.9123.
The specific regex in your problem will depend a lot on the purpose. If you only have a single number in your string, you could do this:
var.replace(/.*?(([0-9]*\.)?[0-9]+).*/g, "$1")
This finds the first number, and replaces the entire string with the matched number.

Try this:
var.replace(/[^0-9\\.]+/g, '');

there's a lot of correct answers already, just pointing out that you might need to account for negative signs too.. "\-" add that to any existing answer to allow for negative numbers.

Try this:
var.replace(/[0-9]*\.?[0-9]+/g, '');
That only matches valid decimals (eg "1", "1.0", ".5", but not "1.0.22")

If you don't want to catch IP address along with decimals:
var.replace(/[^0-9]+\\.?[0-9]*/g, '');
Which will only catch numerals with one or zero periods

How about doing this:
var numbers = str.gsub(/[0-9]*\.?[0-9]+/, "#{0} ");

Sweet and short inline replacing of non-numerical characters in the ASP.Net Textbox:
<asp:TextBox ID="txtJobNo" runat="server" class="TextBoxStyle" onkeyup="this.value=this.value.replace(/[^0-9]/g,'')" />
Alter the regex part as you'ld like. Lots and lots of people complain about the cursor going straight to the end when using the arrow keys, but people tend to deal with this without noticing it for instance, arrow... arrow... arrow... okay then... backspace back space, enter the new chars.

Here are a couple of jQuery input class types I use:
$("input.intgr").keyup(function (e) { // Filter non-digits from input value.
if (/\D/g.test($(this).val())) $(this).val($(this).val().replace(/\D/g, ''));
});
$("input.nmbr").keyup(function (e) { // Filter non-numeric from input value.
var tVal=$(this).val();
if (tVal!="" && isNaN(tVal)){
tVal=(tVal.substr(0,1).replace(/[^0-9\.\-]/, '')+tVal.substr(1).replace(/[^0-9\.]/, ''));
var raVal=tVal.split(".")
if(raVal.length>2)
tVal=raVal[0]+"."+raVal.slice(1).join("");
$(this).val(tVal);
}
});
intgr allows only numeric - like other solutions here.
nmbr allows only positive/negative decimal. Negative must be the first character (you can add "+" to the filter if you need it), strips -3.6.23.333 to -3.623333
I'm putting nmbr up because I got tired of trying to find the way to keep only 1 decimal and negative in 1st position

This one just worked for -ve to +ve numbers
<input type="text" oninput="this.value = this.value.replace(/[^0-9\-]+/g, '').replace(/(\..*)\./g, '$1');">

I use this expression to exclude all non-numeric characters + keep negative numbers with minus sign.
variable.replace(/[^0-9.,\-]/g,'')

Related

check whether csv form or not [duplicate]

What is the regular expression to validate a comma delimited list like this one:
12365, 45236, 458, 1, 99996332, ......
I suggest you to do in the following way:
(\d+)(,\s*\d+)*
which would work for a list containing 1 or more elements.
This regex extracts an element from a comma separated list, regardless of contents:
(.+?)(?:,|$)
If you just replace the comma with something else, it should work for any delimiter.
It depends a bit on your exact requirements. I'm assuming: all numbers, any length, numbers cannot have leading zeros nor contain commas or decimal points. individual numbers always separated by a comma then a space, and the last number does NOT have a comma and space after it. Any of these being wrong would simplify the solution.
([1-9][0-9]*,[ ])*[1-9][0-9]*
Here's how I built that mentally:
[0-9] any digit.
[1-9][0-9]* leading non-zero digit followed by any number of digits
[1-9][0-9]*, as above, followed by a comma
[1-9][0-9]*[ ] as above, followed by a space
([1-9][0-9]*[ ])* as above, repeated 0 or more times
([1-9][0-9]*[ ])*[1-9][0-9]* as above, with a final number that doesn't have a comma.
Match duplicate comma-delimited items:
(?<=,|^)([^,]*)(,\1)+(?=,|$)
Reference.
This regex can be used to split the values of a comma delimitted list. List elements may be quoted, unquoted or empty. Commas inside a pair of quotation marks are not matched.
,(?!(?<=(?:^|,)\s*"(?:[^"]|""|\\")*,)(?:[^"]|""|\\")*"\s*(?:,|$))
Reference.
/^\d+(?:, ?\d+)*$/
i used this for a list of items that had to be alphanumeric without underscores at the front of each item.
^(([0-9a-zA-Z][0-9a-zA-Z_]*)([,][0-9a-zA-Z][0-9a-zA-Z_]*)*)$
You might want to specify language just to be safe, but
(\d+, ?)+(\d+)?
ought to work
I had a slightly different requirement, to parse an encoded dictionary/hashtable with escaped commas, like this:
"1=This is something, 2=This is something,,with an escaped comma, 3=This is something else"
I think this is an elegant solution, with a trick that avoids a lot of regex complexity:
if (string.IsNullOrEmpty(encodedValues))
{
return null;
}
else
{
var retVal = new Dictionary<int, string>();
var reFields = new Regex(#"([0-9]+)\=(([A-Za-z0-9\s]|(,,))+),");
foreach (Match match in reFields.Matches(encodedValues + ","))
{
var id = match.Groups[1].Value;
var value = match.Groups[2].Value;
retVal[int.Parse(id)] = value.Replace(",,", ",");
}
return retVal;
}
I think it can be adapted to the original question with an expression like #"([0-9]+),\s?" and parse on Groups[0].
I hope it's helpful to somebody and thanks for the tips on getting it close to there, especially Asaph!
In JavaScript, use split to help out, and catch any negative digits as well:
'-1,2,-3'.match(/(-?\d+)(,\s*-?\d+)*/)[0].split(',');
// ["-1", "2", "-3"]
// may need trimming if digits are space-separated
The following will match any comma delimited word/digit/space combination
(((.)*,)*)(.)*
Why don't you work with groups:
^(\d+(, )?)+$
If you had a more complicated regex, i.e: for valid urls rather than just numbers. You could do the following where you loop through each element and test each of them individually against your regex:
const validRelativeUrlRegex = /^(^$|(?!.*(\W\W))\/[a-zA-Z0-9\/-]+[^\W_]$)/;
const relativeUrls = "/url1,/url-2,url3";
const startsWithComma = relativeUrls.startsWith(",");
const endsWithComma = relativeUrls.endsWith(",");
const areAllURLsValid = relativeUrls
.split(",")
.every(url => validRelativeUrlRegex.test(url));
const isValid = areAllURLsValid && !endsWithComma && !startsWithComma

Best way to remove thousand separators from string amount using a regex

I have variables that contain amounts and would like to remove the (US) thousand separators but also have to cover the scenario that there may be non-US formatted amounts where the comma is used for the decimals instead of for the thousands where I don't want to replace the comma.
Examples:
1,234,567.00 needs to become 1234567.00
1,234.00 needs to become 1234.00
but
1.234.567,00 needs to remain unchanged as not US format (i.e. comma here is used for decimals)
1.234,00 needs to remain unchanged as not US format (i.e. comma here is used for decimals)
I was thinking of using the following but wasn't sure about it as I am pretty new to Regex:
myVar.replace(/(\d+),(?=\d{3}(\D|$))/g, "$1");
What is best solution here? Note: I just need to cover normal amounts like the above examples, no special cases like letter / number combinations or things like 1,2,3 etc.
This one may suit your needs:
,(?=[\d,]*\.\d{2}\b)
Debuggex Demo
if (string.match(/\.\d{2}$/) {
string = string.replace(',', '');
}
or
string.replace(/,(?=.*\.\d+)/g, '');
Replace /,(?=\d*[\.,])/g with empty string?
http://regexr.com/39v2m
You can use replace() method to remove all the commas. They will be replaced with an empty string. I'm using reg exp with lookahead assertion to detect if a comma is followed by three digits, if so given comma will be removed.
string.replace(/,(?=\d{3})/g, '')
Examples:
'12,345,678.90'.replace(/,(?=\d{3})/g, '')
// '12345678.90'
'1,23,456.78'.replace(/,(?=\d{3})/g, '')
// '1,23456.78'
'$1,234.56'.replace(/,(?=\d{3})/g, '')
// '$1234.56'
This code is worked for me and you can use it in set amount val for remove separators
t.replace(/,(?=\d{3})/g, '')
myVar = myVar.replace(/([.,])(\d\d\d\D|\d\d\d$)/g,'$2');
Removes the period . or comma , when used as a thousand separator.

how to validate a text field in jsp using java script for accepting only dot and comma as special characters

I need to allow only numerics, dot and comma in a text field. If the user enters other special characters an alert needs to be thrown.
Please find below the conditions:
The text field should contain atleast one numeric value.
It is not mandatory that the text field should contain dot and comma always.
Thanks for your help.
Here is a start for you: http://jsfiddle.net/KLyy8/1/
Unless you tell us the exact specifics we won't know how to write the regular expression. Sounds like you want numbers with thousands separator and decimals. But how many of each? The fiddle above will work for numbers like this...
123,456.79
12,345.6
1,234.56
etc...
validate=function(){
var str = document.getElementById('test').value;
var patt = new RegExp("^[0-9]{1,3}\,[0-9]{3}\.[0-9]{1,2}$");
var res = patt.test(str);
alert(res);
}
If the field should contain only numeric values with decimal places (for exmaple 3.14, 112358 or 9,81), then you can use only one regex:
function validateString(str){
if(str.match(^[0-9\.,]+$)){
return true;
}else{
return false;
}
However if you want to be precise you will probably want to limit the dots and commas to one, if I understand your situation correctly.
Regex for that can look like this
^[0-9]+(\.|,){0,1}[0-9]+$
That means it starts with a number (^[0-9]+), then it may contain zero or one times one comma or dot ((\.|,){0,1}) and then again ends with a number ([0-9]+$).

regex search a string for contents between two strings

I am trying my upmost best to get my head around regex, however not having too much luck.
I am trying to search within a string for text, I know how the string starts, and i know how the string ends, I want to return ALL the text inbetween the string including the start and end.
Start search = [{"lx":
End search = }]
i.e
[{"lx":variablehere}]
So far I have tried
/^\[\{"lx":(*?)\}\]/;
and
/(\[\{"lx":)(*)(\}\])/;
But to no real avail... can anyone assist?
Many thanks
You're probably making the mistake of believing the * is a wildcard. Use the period (.) instead and you'll be fine.
Also, are you sure you want to stipulate zero or more? If there must be a value, use + (one or more).
Javascript:
'[{"lx":variablehere}]'.match(/^\[\{"lx":(.+?)\}\]/);
The * star character multiplies the preceding character. In your case there's no such character. You should either put ., which means "any character", or something more specific like \S, which means "any non whitespace character".
Possible solution:
var s = '[{"lx":variablehere}]';
var r = /\[\{"(.*?)":(.*?)\}\]/;
var m = s.match(r);
console.log(m);
Results to this array:
[ '[{"lx":variablehere}]',
'lx',
'variablehere',
index: 0,
input: '[{"lx":variablehere}]' ]
\[\{"lx"\:(.*)\}\]
This should work for you. You can reach the captured variable by \1 notation.
Try this:
^\[\{\"lx\"\:(.*)\}\]$
all text between [{"lx": and }] you will find in backreference variable (something like \$1 , depends on programming language).

Using Regular Expressions with Javascript replace method

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"]

Categories

Resources