Regex to Replace Everything Except Numbers and a Decimal Point

Regex to replace everything except numbers and a decimal point

Use this:

document.getElementById(target).value = newVal.replace(/[^0-9.]/g, '');

Regex Replace all but Numbers and Decimal Place

As you can see in the working fiddle I have created here https://jsfiddle.net/yosefrow/Lscyn8q3/2/

in the processInput function

var processInput = function(inputValue) {
let outputValue = parseFloat(inputValue.replace(/[^.0-9]/g, ''));
console.log("outputValue: " + outputValue);
updateDOM(inputValue, outputValue);
};

The line

outputValue = parseFloat(inputValue.replace(/[^.0-9]/g, ''));

in your implementation compares to

inputValue = $(this).val();
outputValue = parseFloat(inputValue.replace(/[^.0-9]/g, ''));

This means that if your code is not working, it may be related to some pre-processing that is happening before or during the definition of the inputValue

Maybe something is stripping the periods out? Maybe your javascript code is being processed in some way to affect the period in your regular expression?

Edit

Based on the code added, I can safely say that the function stripping out the periods is the parseFloat that is called on each key press. Because parseFloat does not view 1234. as a valid number, it strips it out even though the replace method does not.

You need to add a function that

  1. skips periods
  2. sanity checks double periods. e.g. reduce double periods .. to one period .
  3. ignore periods if a period already exists in the string somewhere

You may also wish to incorporate existing validation methods such as

https://jqueryvalidation.org/number-method/

A simpler approach to validation on the fly might be to simply do a search replace on each key press without using parseFloat.

e.g.

// replace middle non float chars
outputValue = inputValue.replace(/[^.0-9]/g, '')
// replace non number start
outputValue = inputValue.replace(/^[^0-9]/g, '')
// replace double dots
outputValue = inputValue.replace(/\.\./g, '.')

keep in mind it wont resolve ending period '.' so maybe parsefloat before submission

RegEx (replace all non numeric characters and enfore 2 decimal place numbers)

Here is a modified version of your final edit... I added a line to check for the situation: 1.2.3 and replace it with a pattern to remove the second dot. Did it without a look behind because it may not be supported. Here is the line: val = val.replace(/(\.)(.)(\.)/g, ".$2"); The ".$2" will replace the .#. with a dot and the pattern group that is the wildcard (.) in this case. Your other check at the bottom will catch a double dot ".." situation.

$("#amount").on("keyup", function () {
var valid = /^\d{0,9}(\.\d{0,2})?$/.test(this.value);
val = this.value;
console.log("ORIGINAL VAL: " + val);

if (!valid) {
var dotCheck = val.indexOf("..");
if (dotCheck >= 0) {
val = val.replace("..", ".");
}

val = val.replace(/(\.)(.)(\.)/g, ".$2");

//strip out commas
val = val.replace(/,/g, "");

//strip out all non-numeric characters (leaving decimal)
val = val.replace(/[^0-9.]/g, "");

//enforce 2 decimal places (max)
var totalLength = val.length;
var only2DecimalsCount = val.indexOf(".");

if (only2DecimalsCount >= 0 && totalLength > (only2DecimalsCount + 2)) {
val = val.substring(0, (only2DecimalsCount + 3));
}

//output to field
this.value = val;
}
});

EDIT: Fixed new line by adding parenthesis. Explanation: Parenthesis "groups" the pieces of the pattern together (1-based index). So the new linehas 3 groups - (\.)- 1, (.)- 2, (\.)- 3. Replacing with $2 will call group #2 which in this case is the wildcard.

Removing everything except numbers in a string

Note that you should use the correct DOM id to refer via getElementById.
You can use the .replace() method for that:

var loan_amt = document.getElementById('loan_amt');
loan_amt.value = loan_amt.value.replace(/[^0-9]/g, '');

But that will remove float point delimiter too. This is an answer to your question, but not a solution for your problem. To parse the user input as a number, you can use parseFloat() - I think that it will be more appropriate.

Javascript Remove all charater except leading - , one dot and digits

Here I am sharing my solution.

Lets assume the string is a;

//this will convert a to positive integer number
b=a.replace(/[^0-9]/g, '');

//this will convert a to integer number(positive and negative)
b=a.replace(/[^0-9-]/g, '').replace(/(?!^)-/g, '');

//this will convert a to positive float number

b=a.replace(/[^0-9.]/g, '').replace(/(..*)./g, '$1');

//this will convert a to float number (positive and negative)

b=a.replace(/[^0-9.-]/g, '').replace(/(..*)./g, '$1').replace(/(?!^)-/g, '');

Update for floating number.(solves copy paste problem)
//For positive float number
b=a.replace(/[^0-9.]/g, '').replace('.', 'x').replace(/\./g,'').replace('x','.');

//For Negative float number
b=a.replace(/[^0-9.-]/g, '').replace('.', 'x').replace(/\./g,'').replace('x','.').replace(/(?!^)-/g, '');


Related Topics



Leave a reply



Submit