javascript match Regex for numbers and only dot character - javascript

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

Related

Seperate Number and Letter in a String

let input_string='L10M111.05K268.68V 265.42';
let output_string='L 10 M 111.05 K 268.68 V 265.42';
Input string above has both numbers and letters in it which I need to seperate them using space as shown in my output string.
May I know how to achieve this? Any help will be very appreciated :)
One way to do it is to search the string for words (sequential letters) and numbers (digits, followed by an optional period and more digits), and ignore everything else. Then, with those matches, join them all on a single space. You can do that with:
'L10M111.05K268.68V 265.42'.match(/(\d+(\.\d+)?)|[a-zA-Z]+/g).join(' ')
use a regular expression with the replace method to insert spaces between the numbers and letters.
let input_string = 'L10M111.05K268.68V 265.42';
let output_string = input_string.replace(/([a-zA-Z])(\d)/g, '$1 $2');
console.log(output_string);
Here is a modified version that will also process negative numbers and numbers starting with a decimal point:
const res='abc.4L10M_D-111.05K268.68V 265.42 Last-.75end-it-all'.replace(/ *(-?(\.\d+|\d+(\.\d+)?)) */g," $1 ").trim();
console.log(res);

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)))

Regex - How to replace a specific character in a string after being typed only once?

I'm trying to limit an input field to only numbers and the possibility of a "+" sign just at the string's [0] index. The idea is to let the user type their phone number, I have come up with this:
function main() {
let phone = document.getElementById('phone');
let phoneRegex = /[a-zA-Z]|[-!$%^&*()_|~=`{}[\]:";'<>?,./]/;
phone.value = phone.value.replace(phoneRegex, '');
console.log(phone.value);
}
<input id="phone">
<button onclick="main()">Run</button>
The thing is, this works fine, but I want to limit the first character to only a digit or a "+" sign, characters coming from index [1] and on should only be numbers.
I can't come up with an idea on how to solve this
Try this as a starting point (you'll probably want to expand it further to account for total string length, delimiters like -, etc.):
let phoneRegex = /\+?\d+/;
+ in a regular expression has a special meaning, so when we want to match the literal character "+" then we need to escape it. And following it with the ? character makes it optional:
\+?
Next, \d followed by + will match any sequence of one or more digits:
\d+
You can see a visualization of this pattern here.
I want to limit the first character to only a digit or a "+"
sign, characters coming from index [1] and on should only
be numbers.
The regex:
/^\+?\d+$/
means:
From the beginning, one or zero + signs, then one or more numbers until the end.
Note the following regex symbols:
* - zero or more
+ - one or more
? - zero or one
I know I'm late in this game, but adding one more solution for me and other's future references.
I came up with this solution which works for me:
/^(\+|[0-9])?[0-9]{12}$/
Thanks

Regular Expression for negative and positive decimal numbers

I'm trying to create a regular expression using javascript for react application that allow negative and positive decimal numbers and not allow enter any character.
I've been looking for examples, reading documentation but I dont know how make it.
This are the things that have to do:
allow negative and positive decimal numbers, I found this:
var re = new RegExp("^[+-]?[0-9]{0,900}(?:\.[0-9]{0,900})?$");
but I can write a character and show me true and add other character and show me false. console.log(re.test(value));
if is decimal and starts with zero show zero (0.232) and dont allow this (.232)
dont allow write characters, I've seen this /^\d*$/
Looking at the documentation about RegExp it states that when using the constructor function, the normal string escape rules (preceding special characters with \ when included in a string) are necessary.
Your regex would then match a dot which would match any character making for example a valid because the preceding [0-9]{0,900} matches zero - 900 times.
Your regex would become:
var re = new RegExp("^[+-]?[0-9]{0,900}(?:\\.[0-9]{0,900})?$");
To match negative and positive decimal numbers that should not start with a dot, you could use:
^[+-]?[0-9]+(?:\.[0-9]+)?$
Which will match the beginning of the string ^, an optional [+-]?, one or more digits [0-9]+ followed by an optional part which will match a dot and one or more digits (?:\.[0-9]+)? and then the end of the string $.
var re = new RegExp("^-?[0-9]+(?:\\.[0-9]+)?$");
var re = new RegExp("^[+-]?[0-9]+(?:\\.[0-9]+)?$");
var strings = [
"1",
"1.2",
"0.232",
".232",
"-1.2",
"+1.2"
];
strings.forEach((s) => {
console.log(s + " ==> " + re.test(s));
});
I use this:
^-?[0-9]\d*(\.\d+)?$
only numbers
positive and negative
dont allow .232

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

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.

Categories

Resources