I have regex expression which ensures that any characters which do not match the following criteria are replaced by an empty string:
- Must be a number.
- Optionally can be positive or negative.
- Optionally can have decimal values, but not a trailing decimal point.
My problem: I am unable to figure out how to preserve the negative sign if it is found in front of the number. My regex currently replaces all instances of the '-' by an empty string. I am missing something here to ensure this issue does not occur.
var testId = document.getElementById('test');
var validate = value => {
let regex = /([^\d.-]+)|([^\.?\d]+)/g;
return value.toString().trim().replace(regex, '');
};
// Note: in comments, the expected output
var values = [
'12345', // 12345
'-12345', // -12345
'12345.6789', // 12345.6789
'-12345.6789', // -12345.6789
'-123-45.-6789', // -12345.6789
'$12345a6', // 123456
'-1abcde+^~2345.6*#zZ789', // -12345.6789
'50-00', // 5000
'$12345' // 12345
];
values.forEach(value => {
testId.innerHTML += `<p>${value} ==> ${validate(value)}</p>`;
});
<div id="test"></div>