Simple regex. Get the number from [~21~] - javascript

I have a string that looks like this: [~21~]. How can I use regex to only return 21? The number can be any value (numbers), at any length. I am using Javascript with this regex, so if you could include that in your exsample, that would be great.
Thomas

You can:
Remove any other characters than digits
Parse the resulting number to a real number instead of a string
Like:
var number = parseInt(str.replace(/[\D]/g, ""), 10);
Where:
parseInt(..., 10) parses any string to a number in base 10
str.replace(..., "") will remove characters (replace them with nothing)
[\D] means: anything except digits
For example,
parseInt("[~21~]".replace(/[\D]/g, ""), 10) === 21;
Note that it will concatenate numbers in e.g. [~21~22~]; that will become 2122.

A simple regex that will work in your case is:
[0-9]+
This will match a sequence of strings consisting of the characters: 0,1,2,3,4,5,6,7,8,9

If you aren't worried about error-handling:
var getTheNumber = function(a) { return a.substring(0, a.length-2).substring(2); }

-*\d+(\.\d+)*
Contemplates negative and/or decimal numbers. This will extract any number of 1 or more digits no matter the string.

Related

Ignore 2 first characters and select 6 characters of a number and replace to asterisk * with regex

I'm trying to hide/replace with * the 6 middle characters of a number, but I'm not getting the desired result.
Input:
54998524154
Expected output:
54*****154
What I tried:
const phone = "54998524154"
phone.replace(/(?<=^[0-9]{2})([0-9]{6})/g, '*')
It returns
54*154
I also tried replaceAll, but it returns the same result.
Edit: I'd like to achieve it using only one * like:
Replace phone numbers with asterisks pattern by Regex
Regex replace phone numbers with asterisks pattern
Is this what you had in mind? It matches the 3rd through 8th digit successively, replacing each single digit with a single asterisk.
/(?<=^\d{2,7}?)\d/g
It takes advantage of Javascript's ability to specify variable length lookbehinds.
Here it is on Regex101, with your single example:
EDIT
Based on OP's comments, it seems like there may be punctuation between the digits that should be preserved. This approach can be easily extended to ignore non-digits (\D in regex) by adding an optional number of them before and after each digit. Like this:
(?<=^\D*(\d\D*){2,7}?)\d
This will turn (123) 456-7890 into (12*) ***-**90, preserving all punctuation.
If the input is always going to be 11 chars/digits, you could do something like
phone.replace(/(^\d{2})(\d{6})(\d{3}$)/g, "$1******$3");
Explanation:
3 capture groups:
(^\d{2}) - from the beginning of the string, select 2 digits
(\d{6}) - then select 6 digits
(\d{3}$) - Select last 3 digits
Replace pattern:
"$1******$3" - First capture-group, then 6 asterisks, then 3rd capture-group.
You can do this with the below regex.
console.log("54998524154".replace(/(\d{2})\d{6}/,"$1******"))
In fact, you can do it without regex as well.
var numStr = '54998524154';
console.log(numStr.replace(numStr.substring(2,8), "******"));
Without lookarounds, you might also using split check if the characters are digits and then change single digits to * between 2 and 9 characters:
const toAsterix = s => {
let cnt = 0;
return s.split('').map(v => {
const isDigit = /^[0-9]$/.test(v);
if (isDigit) cnt++;
return cnt > 2 && cnt < 9 && isDigit ? "*" : v
}).join('');
}
[
"54998524154",
"(123) 456-7890"
].forEach(s => console.log(toAsterix(s)))

javascript match Regex for numbers and only dot character

I need to match Regex for an input text. It should allow only numbers and only one dot.
Below is my pattren.
(?!\s)[0-9\.\1]{0,}
This is allowing only numbers and allowing multiple dots. How to write so that it should allow only one dot?
Bascially when i enter decimal, i need to round off to whole number.
In case you dont mind accepting just a point, this should do it
\d*\.\d*
Otherwise, the more complete answer could look like this:
\d*\.\d+)|(\d+\.\d*)
You can use the following regex to select your integer and fractional parts than add 1 to your integer part depending to your fractional part:
Regex: ^(\d+)\.(\d+)$
In use:
function roundOff(str) {
return str.replace(/^(\d+)\.(\d+)$/g, ($0, $1, $2) => $2.split('')[0] >= 5 ? parseInt($1) + 1 : parseInt($2));
}
var str1 = roundOff('123.123')
console.log(str1); // 123
var str2 = roundOff('123.567')
console.log(str2); // 124

Float number regex with unexpected results

I'm using this regex to validate float numbers:
var reg = /\d+\.?\d+/;
But it's validating this as true:
"11.34x"
"11.34abs"
"1a1.34abs"
The \d should only match numbers. What is happening?
If you don't anchor the regular expression, it will match a string that contains a substring that matches.
Try:
var reg = /^\d+\.?\d+$/;
The ^ matches the start of the test string, and $ matches the end. Thus that regular expression will only match strings that have nothing but digits and at most one ".".
edit — as pointed out, your use of the + quantifier means your regex requires digits; if there's a decimal point, then it requires digits on both sides. Maybe that's what you want, maybe it isn't.
use this regular expression ^\d+(\.\d+)?$
or ^\d+([.,]\d+)?$ separator can be comma or dot
Consider using the Number wrapper/constructor function instead:
Number('11.34'); // => 11.34
Number('11.34x'); // => NaN
[Edit] As commenter #VisioN points out, that function has an edge case for empty and pure-whitespace strings, so maybe create a wrapper function:
function reallyParseFloatingPointNumber(s) {
var s = (''+s).trim();
return (s==='') ? NaN : Number(s);
}
if (!"12 34.98 ".replace(/^\s+|\s+$/g,"").match(/^\d+\.?\d+$/))
alert("Please enter numbers in float form")
else alert ("Good Form, Old Chap!")
Alas, I am mistaken again! burning_LEGION is correct:
/^\d+(\.\d+)?$/
will match single digits too.

Regex - Quantity Field

I want to validate the contents of a quantity field using Javascript's Regular Expressions.
Valid input would be an integer number, from zero upwards. If leading zeros could be removed too that would be great.
Examples
1 Pass
0 Pass
01 Failed
00 Failed
-1 Failed
1.1 Failed
1000000 Pass
I have tried myself, but the best I got was...
var regex = /[0-9]{1,9}/;
...which doesn't fail on negative numbers, or numbers with leading zeros.
Thanks!
This regular expression matches any sequence of digits without a leading 0 (except for 0 itself, which is handled separately).
var regex = /^0$|^[1-9][0-9]*$/;
^ and $ are anchors, which anchor the match to the beginning and end of the string. This means, nothing is allowed before or after the number, and as such, no minus can be included.
If you want to remove leading zeros instead of forbidding them, then you can use this:
^0*(\d{1,9})$
Now you will find the number without trailing zeros in captured group no. 1 (even if only one 0 was entered).
Try ^\d+$. Should match positive integers.
var re = /^0*([^0]\d*)$/;
var match = re.exec(str);
if (match) {
var i = parseInt(match[1], 10);
}
else {
//whoops, not an integer
}
(match[1] returns the int without leading zeroes, match[0] the entire matched string).

Replace numbers in Javascript

I have this string: £0,00
Which i want to replace with float 3.95 for instance. But i want to keep the £ and the ","
So result -> £3,95
How would i do it?
--
Added some details:
Will the currency symbol always be a £?
The currency symbol might be before and sometimes behind the numbers. ie 0,00 kr
Will the separator always be ,, or might it be . or even an arbitrary character?
The separator might be . sometimes.
Will there always be two decimal places?
The decimal will always be 2 places.
How many integer digits might there be, and will there be a thousands separator?
It will not be above 100.
function convert (proto, value) {
return proto.replace (/0(.)00/, function (m, dp) {
return value.toFixed (2).replace ('.', dp);
});
}
the proto parameter specifies the format, it must have a sub-string consisting of a single 0 digit followed by any character followed by two 0 digits, this entire sub-string is replaced by the numeric value parameter replacing the decimal point with the character between the 0 digits in the proto.
<script type="text/javascript">
function Convert(Value) {
return '£' + Value.toString().replace('.', ',');
}
alert(Convert(3.95));
</script>
Regular expression /(\D*)\s?([\d|.|,]+)\s?(\D*)/ will return an array with following values:
[0] = whole string (eg "£4.30"
[1] = prefix (eg. "£")
[2] = numerical value (eg. "4.30")
[3] = suffix (eg. "kr")
Usage: var parts = /(\D*)\s?([\d|.|,]+)\s?(\D*)/.exec(myValue);
It also handles cases where either prefix or suffix has following or leading space.
And whenever you need to replace the comma from number, just use the value.replace(",",".") method.

Categories

Resources