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

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},}`);

Related

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.

regex to replace anything that is not a number or period in string [duplicate]

This question already has answers here:
Regex to replace everything except numbers and a decimal point
(7 answers)
Closed 3 years ago.
I am trying to write a regex that replaces anything that isn't a digit or a . in a string.
For example:
const string = 'I am a 1a.23.s12h31 dog'`
const result = string.replace(/[09.-]/g, '');
// result should be `1.23.1231`
Can anyone see what I am doing wrong here.
You could change your regex to [^0-9.]+:
const result = string.replace(/[^0-9.]+/g, "");
Alternatively, if you don't want a regex, use split and filter, then join:
const result = string.split("").filter(s => isNaN(s) || s == ".").join("");

Matching list symbols in regex (angular 2) [duplicate]

This question already has answers here:
Why do regex constructors need to be double escaped?
(5 answers)
Closed 4 years ago.
I am trying to match the list of symbols in regex but somehow the result is always returning with errors
symbol list = !##$+*{}?<>&’”[]=%^
if (text.match('^[\[\]\!\"\#\$\%\&\'\(\)\*\+\,\/\<\>\=\?\#\[\]\{\}\\\\\^\_\`\~]+$')) {
this.specialChar = true;
} else {
this.specialChar = false;
}
I am getting the following error:
Invalid regular expression: /^[[]!"#$%&'()*+,/<>=?#[]{}\\^_`~]+$/: Nothing to repeat
How do I correctly match the symbols in regex? basically I want to check if text contain any of those symbols.
You should use this regex constructor instead:
if (text.match(/^[\[\]\!\"\#\$\%\&\'\(\)\*\+\,\/\<\>\=\?\#\[\]\{\}\\\\\^\_\`\~]+$/)) {
this.specialChar = true;
} else {
this.specialChar = false;
}
The reason it fails is that you use a regex string constructor. If you still want to do that, you need to DOUBLE escape the characters, like this:
if (text.match('^[\\[\\]\\!\\"\\#\\$\\%\\&\\'\\(\\)\\*\\+\\,\\/\\<\\>\\=\\?\\#\\[\\]\\{\\}\\\\\\^\\_\\`\\~]+$')) {
Now you will create a valid regex.

Matching exactly 10 digits in Javascript [duplicate]

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

Don't add whitespace as part of the values length in Javascript? [duplicate]

This question already has answers here:
Trim string in JavaScript
(20 answers)
Closed 8 years ago.
I have an if statement to check whether there is at least 15 characters before the textarea is considered valid in my form. I don't mind users adding whitespace but, I don't want it to count as part of the length for the value.
if(userApplying.value.length <= 14){
document.getElementById("applying_error").innerHTML =
"* please enter at least 15 characters in your message."
error = true;
}//end of if
Answer in Javascript please.
You can use the String.replace() function in conjunction with a regular expression to create a new variable that is equivalent to the original input but with the spaces removed, and then use that for your test:
var inputWithSpacesRemoved = originalInput.replace(/\s*/g, '');
if (isNormalizedInputValid(inputWithSpacesRemoved)) {
// ...
}
In the above, I'm assuming you've tidied up things a little bit:
var isNormalizedInputValid = function(normalizedInput) {
return normalizedInput.length < 15;
};
And:
var originalInput = userApplying.value;

Categories