Live control a float input with a regex mask - javascript

I've made a function to live control numbers and float numbers.
But it doesn't work properly for float numbers, which have to be like this expression:
// I wish a number like x figures . 3 figures (example : 123456.123)
/^([1-9][0-9]*|0)(\.[0-9]{3})?$/
But this expression makes disappear the dot...
The follow works /(^\d+$)|(^\d+\.\d+$)|[,.]/, but multiple dots can be added:
$('.float_input').live("keypress",function(){inputControl($(this),'double');});
function inputControl(input,format)
{
var value=input.val();
if (format=='int'){expression=/(^\d+$)|(^\d+\.\d+$)/;}
else if (format=='double'){expression=/(^\d+$)|(^\d+\.\d+$)|[,.]/;}
var values=value.split("");
var update="";
for(id in values)
{
if (expression.test(values[id])==true && values[id]!='')
{
// also replace ',' by '.'
update=update+''+values[id].replace(',','.');
}
}
input.val(update);
}
So I have multiple dots or no dot, it makes me nutty because I'm sure to be near the solution.
EDIT > SOLUTION
Ouch, thanks for the help about regex, I've found the solution!
Two tests were necessary:
one for the characters test, tested one by one
another to test the entire input while entering characters
This is the final script, which works like a flower, and I share it just for you:
$('.numeric_input').live("keyup",function(){inputControl($(this),'int');});
$('.float_input').live("keyup",function(){inputControl($(this),'float');});
function inputControl(input,format)
{
var value=input.val();
var values=value.split("");
var update="";
var transition="";
if (format=='int'){
expression=/^([0-9])$/;
finalExpression=/^([1-9][0-9]*)$/;
}
else if (format=='float')
{
var expression=/(^\d+$)|(^\d+\.\d+$)|[,\.]/;
var finalExpression=/^([1-9][0-9]*[,\.]?\d{0,3})$/;
}
for(id in values)
{
if (expression.test(values[id])==true && values[id]!='')
{
transition+=''+values[id].replace(',','.');
if(finalExpression.test(transition)==true)
{
update+=''+values[id].replace(',','.');
}
}
}
input.val(update);
}

This regex
(/(^\d+$)|(^\d+.\d+$)|[,.]/)
should match
1111111 per the (^\d+$)
or 111111.11111 per the (^\d+.\d+$)
or the comma followed by any character, and it could be anywhere in the expression.
I'm suspecting your regex should be
Note that I've escaped the final period. That would match a comma or a period
/(^\d+[,\.]{0,1}\d{3})/
may be exactly what you want based on clarifications in the comments
[-+]?[0-9]*\.?[0-9]+
would also work
NOTE: You can simplify your regex life tremendously by using Roy Osherove's Regulazy or the tool Regex Buddy.

You want arbitrary amount of digits behind the decimal point (comma or period)?
What's wrong with:
/^([1-9][0-9]*|0)([\.,][0-9]+)?$/
I switched out the {3} for + and \. for [\.,]

Related

Using javascript or python regular expressions I want to determine if the number is 1-99 how to make it?

var category = prompt("where do you go? (1~99)", "");
hello
Using regular expressions I want to determine if the category is 1-99.
How can I solve it?
Thank you if you let me know.
You can use character classes to match digits, like this [0-9]. If you put two of them together you'll match 00 - 99. If you put a ? after one of them, then it's optional, so you'll match 0 - 99. To enforce 1-99, make the non-optional one like this [1-9]. Finally, you need to make sure there's nothing before or after the one or two digits using ^, which matches the beginning of the string, and $ which matches the end.
if (category.match(/^[1-9][0-9]?$/)){
console.log("ok")
} else {
console.log("not ok")
}
In JavaScript you can use test() method with RE for 1-99 as shown below:
var one_to_ninetynine = /^[1-9][0-9]?$/i;
if(one_to_ninetynine.test(category)) {
console.log("The number is between 1-99");
} else {
console.log("The number is NOT between 1-99");
}

Mixed results with White Spaces, and add a dash in Javascript?

How do you combine eliminating white-spaces and special characters with only a single '-' character?
Here's a little Background:
When publishing a job to my career section for my company, the ATS will turn a job title for the URL, e.g if a job title is:
Olympia, WA: SLP Full or Part Time it will become olympia-wa-slp-full-or-part-time
I've experimented from other similar questions, but have only come close with this bit of code:
function newTitle(str) {
var x = str.replace(/[\W]/g, '-').toLowerCase();
return x;
now if I run it, the output generated is olympia--wa--slp-full-or-part-time
(has 2 dashes from the extra spaces). What am I not getting right?
I've tried the other following bits:
str.replace(/\s+/g, '');
and
str.replaceAll("[^a-zA-Z]+", " ");
but neither get close to the desired format.
Thanks!
You got pretty close in your first example, just add + after [\W] to match one or more non-word characters. You can also give it a try in Regexr
function newTitle(str) {
var x = str.replace(/[\W]+/g, '-').toLowerCase();
return x;
}
alert(newTitle('Olympia, WA: SLP Full or Part Time'));
What you actually want, it looks like, is to create a slug from a string.
Here is a nice reusable function that also takes care of multiple dashes:
function slugify(s) {
s = s.replace(/[^\w\s-]/g, '').trim().toLowerCase();
s = s.replace(/[-\s]+/g, '-');
return s;
}
console.log(
slugify("Olympia, WA: SLP Full or Part Time")
);
Your last example [^a-zA-Z]+ almost works if you use a dash as the replacement. This uses a negated character class to match not what you specified so that would include whitespaces and special characters.
Note that if you have a job with for example a digit or an underscore that that would also be replaced. Your could expand the character class with what you don't want to be replaced like [^a-zA-Z0-9]+ or if you also want to keep the underscore \W+ as that would match [^a-zA-Z0-9_]
function newTitle(str) {
return str.replace(/[^a-zA-Z]+/g, '-').toLowerCase();
}
console.log(newTitle("Olympia, WA: SLP Full or Part Time"));

syntax error on function to detect non-alphanumeric characters in a value?

I know that there are hundreds( or likely thousands) of questions regarding regex functions in this forum. I have read and consulted several, and by all presumptions, I ought to have the answer, and my function ought to work, but it isn't.
I have tried to build a function, in which one of the checks is for only allowing alpha-numeric characters.
The abridged version of the code is this:
function functionName() {
var x = $("#inputId").val();
//trying to locate any/all non alphanumeric characters & spaces
var regex = /^[^0-9a-zA-Z\s]+$/g
if ( x.indexOf(regex) >= 0 ){
alert("message");
return false;
}
}
Does anyone know where I am going wrong?
Thanks
You shouldn't be using indexOf; you should be using test. That's also a little bit of a funny regex you're using. I've modified it below to match valid strings instead of invalid.
function functionName(){
var x = $("#inputId").val();
var regex = /^[a-zA-Z0-9]+$/g;
if ( x.test(regex) ){
alert("Only contains alphanumeric characters. No punctuation or spaces!");
} else {
return false;
}
}
You regex matches only strings that consist entirely of invalid characters. What you really want is one matching when there is at least one invalid character
var regex = /[^0-9a-zA-Z\s]/;
if (regex.test(x)) ...
Your are missing the final '}'

Allow negative/positive numbers but not letters

I want to disable letters in my textbox, that's why I used this expression:
/^[0-9]*$/
The problem is that I want to allow negative numbers too,
and this expression does'nt enable me to use minus sign.(-)..
What shuold I do?
Try with following regexp:
/^-?[0-9]*$/
More correctly: /^(?:- *)?[0-9]+$/
Since it is usually allowed to have one or more spaces between the minus sign and the digits. Also, you must have at least one digit to have a valid number.
If you decide you want to match all kinds of numbers, including floating point, this is a good read. If you just want to match simple integers with an optional "minus" sign, then go with hsz's answer, though I might change the * to a +.
Use the isNaN() function of JavaScript.
Here is a code below:
$(document).ready(function () {
numbersPlusMinus();
});
function numbersPlusMinus() {
var inputPrev = "";
$(".toNumberPlusMinus").change(function () {
if (isNaN($(this).val())) {
$(this).val(inputPrev);
} else {
inputPrev = $(this).val();
}
});
}

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