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

First of all this question is not same as
strip non-numeric characters from string or
Regex to replace everything except numbers and a decimal point
I want to convert a string with valid number like.
--1234// will be -1234
-123-123 will be -123123
12.123.3 will be 12.1233
-123.13.123 will be -123.13123
I tried those
number.replace(/[^0-9.-]/g, '') //it accepts multiple . and -
number.replace(/[^0-9.]-/g, '').replace(/(\..*)\./g, '$1');//it accepts multiple minus
I am facing Problem with leading minus sign.
How I can convert a string which will remove all characters except leading -(remove other minus),digits and only one dot(remove other dots)

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, '');

Based on #Shaiful Islam's answer, I added one more code.
var value = number
.replace(/[^0-9.-]/g, '') // remove chars except number, hyphen, point.
.replace(/(\..*)\./g, '$1') // remove multiple points.
.replace(/(?!^)-/g, '') // remove middle hyphen.
.replace(/^0+(\d)/gm, '$1'); // remove multiple leading zeros. <-- I added this.
Result
00.434 => 0.434

Not very clean, but works!
var strings = ["-1234","-123-123","12.123.3", "-123.13.123"];
strings.forEach(function(s) {
var i = 0;
s = s.replace(/(?!^)-/g, '').replace(/\./g, function(match) {
return match === "." ? (i++ === 0 ? '.' : '') : '';
});
console.log(s);
});

In your sample data given below,
--1234
-123-123
12.123.3
-123.13.123
-(minus sign or hyphen) causes no problem because it's place is only before digits and not between digits. So this can be solved using following regex.
Regex: -(?=-)|(?<=\d)-(?=\d+(-\d+)?$) and replace with empty string.
Regex101 Demo
However, the position of .(decimal) cannot be determined. Because 123.13.123 could also mean 123.13123 and 12313.123.

Without regex, you can map over the characters this way:
// this function takes in one string and return one integer
f=s=>(
o='', // stands for (o)utput
d=m=p=0, // flags for: (d)igit, (m)inus, (p)oint
[...s].map(x=> // for each (x)char in (s)tring
x>='0'&x<='9'? // if is number
o+=x // add to `o`
:x=='-'? // else if is minus
m||(p=0,m=o=x) // only if is the first, reset: o='-';
:x=='.'? // else if is point
p||(p=o+=x) // add only if is the first point after the first minus
:0), // else do nothing
+o // return parseInt(output);
);
['--1234','-123-123','12.123.3','-123.13.123'].forEach(
x=>document.body.innerHTML+='<pre>f(\''+x+'\') -> '+f(x)+'</pre>')
Hope it helps.

My solution:
number.replace(/[^\d|.-]/g, '') //removes all character except of digits, dot and hypen
.replace(/(?!^)-/g, '') //removes every hypen except of first position
.replace(/(\.){2,}/g, '$1') //removes every multiplied dot
It should then formatted to the proper locale setting using Intl.NumberFormat.

Related

jQuery: Unable to use RegExp to search for exactly "+3.00" or "-3.00"

I'm struggling with finding the correct RegExp to match number with plus (+) or minus (-) sign at the end.
I have a select list of number ranging from 0.00- to 40.00- and 0.00+ to 40.00-. I'm using the following RegExp to filter out non matching records:
$("#MySelectBox").change(function() {
var filter = $(this).val()
// If the list item does not contain the numbers phrase fade it out
if ($(this).text().search(new RegExp('\\b'+filter+'\\b', "i")) < 0) {
$(this).hide();
} else {
$(this).show();
}
However, it will show both + and - numbers. For example: if filter = 3.00+ then it will return both 3.00+ and 3.00- values.
Any ideas how to get the exact match?
[\+-]\d{1,2}\.00
Will match + or -, followed by one or two digits (\d{1,2}), followed by .00.
However, RegExes don't have "greater than 40" kind of logic. They only match patterns.
There are useful tools to help you, like Rexegpal
So with your brief:
Check string matches pattern: "+xx.xx" or "-xx.xx"
Only numbers between -40 or +40
Omit results out of bounds
This could be a good way to achieve your desired result.
Notes: (1) Unsure if you wanted to enforce the demical point, (2) there are certainly multiple ways to achieve your result, this is is just one.
const regex = /^[\-\+]\d+\.*\d*$/;
const tests = ["41", "20", "+20", "-20", "+20.00", "-20.20", "20.20"];
const passedTests = tests.filter(number => {
const parsedNumber = Number.parseFloat(number);
const isValid = !!number.match(regex) && parsedNumber > -40 && parsedNumber < 40;
console.log(`Test ${number}, result: ${isValid}`);
return isValid;
});
console.log(passedTests);
To get an exact match for a number with plus (+) or minus (-) sign at the end and from 0.00- to 40.00- and 0.00+ to 40.00+, you can use:
^(?:(?:[0-9]|[123]\d)\.\d\d|40\.00)[+-]$
^ Start of string
(?: Non capture group for the alternation |
(?:[0-9]|[123]\d) Match either a digit 0-9 or a number 10 - 39
\.\d\d Match a . and 2 digits 0-9
| Or
40\.00 Match 40.00
) Close group
[+-] Match either + or -
$ End of string
Regex demo
In Javascript you can use
const regex = /^(?:(?:[0-9]|[123]\d)\.\d\d|40\.00)[+-]$/;
If the value is not the only value in the string, you could start with pattern with a word boundary \b and assert a whitespace boundary at the right (?!\S)
\b(?:(?:[0-9]|[123]\d)\.\d\d|40\.00)[+-](?!\S)
Regex demo

regex: remove leading zeros, but keep single zero

I have an input field to which I have tied a formatting function that is triggered whenever the field loses focus.
What I aim to achieve is that I remove all the leading zeros from an input and I did achieve that with the below line. However, when the user wants to enter a single 0 or something like 0000 I still want that field to end with the value 0 (single). With .replace(/^0+/, '') it would remove every zero and return just an empty string. Someone knows what regex could handle this?
const formatNumber = ($field) => {
var number = $field.val().replace(/\./g, '').replace(/\s/g, '').replace(/^0+/, '');
return number;
};
note: if(number === "") number = "0" is not an option.
edit1:: I noticed there seems to be a bit of confusion. e.g "0009825" need to become 9825 and not 09825. the only instance where i want a 0 up front is when the value is simply zero.
You ay use this regex replacement:
.replace(/^(?:0+(?=[1-9])|0+(?=0$))/mg, '')
RegEx Demo
RegEx Details:
^: Start
(?:: Start capture group
0+(?=[1-9]): Match 1 or more zeroes that must be followed by 1-9
|: OR
0+(?=0$): Match 1 or more zeroes that must be followed by one 0 and end
): End capture group
Replacement is empty string which will leave a single 0 if there are only zeroes in string otherwise will remove leading zeroes.
Alternative solution using a capture group:
str = str.replace(/^0+(0$|[1-9])/mg, '$1');
A simple reg exp with leading zeros and match one digit in a capture group
const cleanZeros = str => str.replace(/^0+(\d)/, '$1')
var tests = ["0009876","0", "0000", "9999", "0090000"]
tests.forEach( s => console.log(s, cleanZeros(s)))

Javascript Regular Expression for numbers

I am trying to make a HTML form that accepts a rating through an input field from the user. The rating is to be a number from 0-10, and I want it to allow up to two decimal places. I am trying to use regular expression, with the following
function isRatingGood()
{
var rating = document.getElementById("rating").value;
var ratingpattern = new RegExp("^[0-9](\.[0-9][0-9]?)?$");
if(ratingpattern.test(rating))
{
alert("Rating Successfully Inputted");
return true;
}
else
{
return rating === "10" || rating === "10.0" || rating === "10.00";
}
}
However, when I enter any 4 or 3 digit number into the field, it still works. It outputs the alert, so I know it is the regular expression that is failing. 5 digit numbers do not work. I used this previous answer as a basis, but it is not working properly for me.
My current understanding is that the beginning of the expression should be a digit, then optionally, a decimal place followed by 1 or 2 digits should be accepted.
You are using a string literal to created the regex. Inside a string literal, \ is the escape character. The string literal
"^[0-9](\.[0-9][0-9]?)?$"
produces the value (and regex):
^[0-9](.[0-9][0-9]?)?$
(you can verify that by entering the string literal in your browser's console)
\. is not valid escape sequence in a string literal, hence the backslash is ignored. Here is similar example:
> "foo\:bar"
"foo:bar"
So you can see above, the . is not escaped in the regex, hence it keeps its special meaning and matches any character. Either escape the backslash in the string literal to create a literal \:
> "^[0-9](\\.[0-9][0-9]?)?$"
"^[0-9](\.[0-9][0-9]?)?$"
or use a regex literal:
/^[0-9](\.[0-9][0-9]?)?$/
The regular expression you're using will parsed to
/^[0-9](.[0-9][0-9]?)?$/
Here . will match any character except newline.
To make it match the . literal, you need to add an extra \ for escaping the \.
var ratingpattern = new RegExp("^[0-9](\\.[0-9][0-9]?)?$");
Or, you can simply use
var ratingPattern = /^[0-9](\.[0-9][0-9]?)?$/;
You can also use \d instead of the class [0-9].
var ratingPattern = /^\d(\.\d{1,2})?$/;
Demo
var ratingpattern = new RegExp("^[0-9](\\.[0-9][0-9]?)?$");
function isRatingGood() {
var rating = document.getElementById("rating").value;
if (ratingpattern.test(rating)) {
alert("Rating Successfully Inputted");
return true;
} else {
return rating === "10" || rating === "10.0" || rating === "10.00";
}
}
<input type="text" id="rating" />
<button onclick="isRatingGood()">Check</button>
Below find a regex candidate for your task:
^[0-1]?\d(\.\d{0,2})?$
Demo with explanation
var list = ['03.003', '05.05', '9.01', '10', '10.05', '100', '1', '2.', '2.12'];
var regex = /^[0-1]?\d(\.\d{0,2})?$/;
for (var index in list) {
var str = list[index];
var match = regex.test(str);
console.log(str + ' : ' + match);
}
This should also do the job. You don't need to escape dots from inside the square brackets:
^((10|\d{1})|\d{1}[.]\d{1,2})$
Also if you want have max rating 10 use
10| ---- accept 10
\d{1})| ---- accept whole numbers from 0-9 replace \d with [1-9]{1} if don't want 0 in this
\d{1}[.]\d{1,2} ---- accept number with two or one numbers after the coma from 0 to 9
LIVE DEMO: https://regex101.com/r/hY5tG4/7
Any character except ^-]\ All characters except the listed special characters are literal characters that add themselves to the character class. [abc] matches a, b or c literal characters
Just answered this myself.
Need to add square brackets to the decimal point, so the regular expression looks like
var ratingpattern = new RegExp("^[0-9]([\.][0-9][0-9]?)?$");

Extend a regular expression to negative number

I want to extend the following regex to negative numbers.
this.value = this.value.replace(/[^0-9\.]/g, "");
I tried adding minus sign doing something like this, (/[^-0-9.]/g, "") but this allows minus sign to be entered anywhere in the number. I want to allow only one occurance of the minus sign at the beginning of the number. Later occurances of minus should be ignored.
Please help.
Uh, replacing every non-number character makes that a bit harder - it's like "negating" the regex. What I came up with is a negative lookahead, preventing a minus - which would be matched by [^0-9.] - from beeing matched if it is in the beginning of the string (using a start anchor):
….replace(/(?!^-)[^0-9.]/g, "")
Why RegEx? How about:
var temp = parseFloat(this.value)
this.value = isNaN(temp) ? "" : temp;
This should also work:
var temp = +this.value;
this.value = isNaN(temp) ? "" : temp;
Put your dash outside of the character class:
this.value = this.value.replace(/^-?[^0-9\.]/g, "");
The regex in provided by you is faulty for the positive numbers itself as it will convert "100+200=300" to "100200300".
I suggest you try this:
someString.match(/-?[\d]+.?[\d]*/);
It is only to put the negative symbol in front of the 0
this.value = this.value.replace(/[^-0-9\.]/g, "");

What's a good RegExp that will strip out all characters except Integers from a string?

I'm new to using regexp, can someone give me the regexp that will strip out everything but an integer from a string in javascript?
I would like to take the string "http://www.foo.com/something/1234/somethingelse" and get it down to 1234 as an integer.
Thanks
var str = "something 123 foo 432";
// Replace all non-digits:
str = str.replace(/\D/g, '');
alert(str); // alerts "123432"
In response to your edited question, extracting a string of digits from a string can be simple, depending on whether you want to target a specific area of the string or if you simply want to extract the first-occurring string of digits. Try this:
var url = "http://www.foo.com/something/1234/somethingelse";
var digitMatch = url.match(/\d+/); // matches one or more digits
alert(digitMatch[0]); // alerts "1234"
// or:
var url = "http://x/y/1234/z/456/v/890";
var digitMatch = url.match(/\d+/g); // matches one or more digits [global search]
digitMatch; // => ['1234', '456', '890']
This is just for integers:
[0-9]+
The + means match 1 or more, and the [0-9] means match any character from the range 0 to 9.
uri = "http://www.foo.com/something/1234/somethingelse";
alert(uri.replace(/.+?\/(\d+)\/.+/, "$1"))
Just define a character-class that requires the values to be numbers.
/[^0-9]/g // matches anything that is NOT 0-9 (only numbers will remain)

Categories