Matching exactly 10 digits in Javascript [duplicate] - javascript

This question already has answers here:
Match exact string
(3 answers)
Closed 4 years ago.
I've tried other questions on SO but they don't seem to provide a solution to my problem:
I have the following simplified Validate function
function Validate() {
var pattern = new RegExp("([^\d])\d{10}([^\d])");
if (pattern.test(document.getElementById('PersonIdentifier').value)) {
return true;
}
else {
return false;
}
}
I've tested to see if the value is retrieved properly which it is. But it doesn't match exactly 10 digits. I don't want any more or less. only accept 10 digits otherwise return false.
I can't get it to work. Have tried to tweak the pattern in several ways, but can't get it right. Maybe the problem is elsewhere?
I've had success with the following in C#:
Regex pattern = new Regex(#"(?<!\d)\d{10}(?!\d)")
Examples of what is acceptable:
0123456789
,1478589654
,1425366989
Not acceptable:
a123456789
,123456789a
,a12345678a

You can try with test() function that returns true/false
var str='0123456789';
console.log(/^\d{10}$/.test(str));
OR with String#match() function that returns null if not matched
var str='0123456789';
console.log(str.match(/^\d{10}$/));
Note: Just use ^ and $ to match whole string.

You can use this:
var pattern = /^[0-9]{10}$/;

You can try this :
var str = "0123456789";
var pattern = new RegExp("^[0-9]{10}$");
pattern.test(str);

Related

JS RegExp with StringLiteral in match() issue [duplicate]

This question already has answers here:
Why do regex constructors need to be double escaped?
(5 answers)
Closed 2 years ago.
If I use this....
var str = 'Testing123##';
if (str.match(/^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9])(?=.*?[!,%,&,#,#,$,^,*,?,_,~,+,\-,",',.,:,=,{,},\[,\],(,)]).{8,}/)) {
args.IsValid = true;
}
This works fine.
But I updated to try and use a StringLiteral for the '8' so in theory it could be dynamic.
var passwordMinLength = 8;
const regex = new RegExp(`^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9])(?=.*?[!,%,&,#,#,$,^,*,?,_,~,+,\-,",',.,:,=,{,},\[,\],(,)]).{${passwordMinLength},}`);
if (str.match(regex)) {
args.IsValid = true;
}
Though, this returns false even though in the JS debugger the string output looks the same as the previous implementation. The 8 is showing up as expected.
The two regexes are different due to string interpolation. See this comparison from my Notepad++:
You need:
const regex = new RegExp(`^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9])(?=.*?[!,%,&,#,#,$,^,*,?,_,~,+,\\-,",',.,:,=,{,},\\[,\\],(,)]).{${passwordMinLength},}`);

Regex validation within if statements [duplicate]

This question already has answers here:
Check whether a string matches a regex in JS
(13 answers)
Closed 8 months ago.
Hi I am hoping this may be and easy one for some of you.
Essentially I am just asking if it is possible to use a regex match statement within a if statement.
I have used some in my Formik validation schema but am not sure if it is possible to use within an if statement.
This is my if statement
if (this.state.email.length < 8 || this.state.password.length < 8)
I would like to include something along the logic of
.matches(/(?=.*outlook)/)
Is this possible ?
I think what you're looking for is the regex .test() method. It applies a regex to a string and returns true if it matches, or false if it doesn't. See here:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/test
you can use match to validate regex expression in javascript, this is an example of email validation :
function ValidateEmail(inputText) {
var mailformat = /^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/;
if (inputText.match(mailformat)) return true;
}

Same regex have different results in Java and JavaScript [duplicate]

This question already has answers here:
Difference between matches() and find() in Java Regex
(5 answers)
Closed 3 years ago.
Same regex, different results;
Java
String regex = "Windows(?=95|98|NT|2000)";
String str = "Windows2000";
Pattern p = Pattern.compile(regex);
Matcher m = p.matcher(str);
System.out.println(m.matches()); // print false
JavaScript
var value = "Windows2000";
var reg = /Windows(?=95|98|NT|2000)/;
console.info(reg.test(value)); // print true
I can't understand why this is the case?
From the documentation for Java's Matcher#matches() method:
Attempts to match the entire region against the pattern.
The matcher API is trying to apply your pattern against the entire input. This fails, because the RHS portion is a zero width positive lookahead. So, it can match Windows, but the 2000 portion is not matched.
A better version of your Java code, to show that it isn't really "broken," would be this:
String regex = "Windows(?=95|98|NT|2000)";
String str = "Windows2000";
Pattern p = Pattern.compile(regex);
Matcher m = p.matcher(str);
while (m.find()) {
System.out.println(m.group()); // prints "Windows"
}
Now we see Windows being printed, which is the actual content which was matched.

Looking to trim a string using javascript / regex [duplicate]

This question already has an answer here:
Reference - What does this regex mean?
(1 answer)
Closed 4 years ago.
I'm looking for some assistance with JavaScript/Regex when trying to format a string of text.
I have the following IDs:
00A1234/A12
0A1234/A12
A1234/A12
000A1234/A12
I'm looking for a way that I can trim all of these down to 1234/A12. In essence, it should find the first letter from the left, and remove it and any preceding numbers so the final format should be 0000/A00 or 0000/AA00.
Is there an efficient way this can be acheived by Javascript? I'm looking at Regex at the moment.
Instead of focussing on what you want to strip, look at what you want to get:
/\d{4}\/[A-Z]{1,2}\d{2}/
var str = 'fdfhfjkqhfjAZEA0123/A45GHJqffhdlh';
match = str.match(/\d{4}\/[A-Z]{1,2}\d{2}/);
if (match) console.log(match[0]);
You could seach for leading digits and a following letter.
var data = ['00A1234/A12', '0A1234/A12', 'A1234/A12', '000A1234/A12'],
regex = /^\d*[a-z]/gi;
data.forEach(s => console.log(s.replace(regex, '')));
Or you could use String#slice for the last 8 characters.
var data = ['00A1234/A12', '0A1234/A12', 'A1234/A12', '000A1234/A12'];
data.forEach(s => console.log(s.slice(-8)));
You could use this function. Using regex find the first letter, then make a substring starting after that index.
function getCode(s){
var firstChar = s.match('[a-zA-Z]');
return s.substr(s.indexOf(firstChar)+1)
}
getCode("00A1234/A12");
getCode("0A1234/A12");
getCode("A1234/A12");
getCode("000A1234/A12");
A regex such as this will capture all of your examples, with a numbered capture group for the bit you're interested in
[0-9]*[A-Z]([0-9]{4}/[A-Z]{1,2}[0-9]{2})
var input = ["00A1234/A12","0A1234/A12","A1234/A12","000A1234/A12"];
var re = new RegExp("[0-9]*[A-Z]([0-9]{4}/[A-Z]{1,2}[0-9]{2})");
input.forEach(function(x){
console.log(re.exec(x)[1])
});

Pattern check returning false javascript/typescript [duplicate]

This question already has answers here:
JavaScript RegExp objects
(5 answers)
Closed 6 years ago.
I am trying to validate if a string I entered matches the date format 'MM/yyyy'
Below is a sample of the code I am using for the same:
var date='05/2016'
var patt= new RegExp('^((0[1-9])|(1[0-2])|[1-9])\/(\d{4})$');
patt.test(date);
However the above code is returning false.
I tried running it with the regex checker:
https://regex101.com/
The pattern seems to be working fine.
Could someone please let me know what is missing.
https://jsfiddle.net/ymj6o8La/
You have to escape the string that is passed to RegExp (the backslashes).
var patt= new RegExp('^((0[1-9])|(1[0-2])|[1-9])\\/(\\d{4})$');
Even better, in your case, it's not dynamic, so you should use the literal RegExp instead
var patt = /^((0[1-9])|(1[0-2])|[1-9])\/(\d{4})$/
You should escape your backslashes. To represent \d or even \ you should another backslash behind it (e.g: \\) :
var date = '05/2016'
var patt = new RegExp('^((0[1-9])|(1[0-2])|[1-9])\\/(\\d{4})$');
console.log(patt.test(date));
Try using a pattern like this
patt= /^((0[1-9])|(1[0-2]))\/(\d{4})$/;

Categories