javascript regular expression for atleast one number and one uppercase letter - javascript

what would be the regular expression to check if a given string contains atleast one number and one uppercase letter?
Thanks in advance
I am doing like this
function validate_pass{
var var_password = document.getElementById("npassword").value;
else if (!(/^(?=.*\d)(?=.*[A-Z]).+$/).test(var_password))){
msg = "Password should contain atleast.";
showErrorMsgPassword(msg);
$('#npassword').val('');
$('#cpassword').val('');
return false;
}
else return true;

If the desire is to test a string to see if it has a least one digit and at least one uppercase letter in any order and with any other characters allowed too, then this will work:
var str = "abc32Qdef";
var re = /[A-Z].*\d|\d.*[A-Z]/;
var good = re.test(str);​
Working demo with a bunch of test cases here: http://jsfiddle.net/jfriend00/gYEmC/

It's been a while since I've done this, and I'm fairly certain there is a more efficient way than this. You will need to use positive lookaheads, but there should be a way to remove the wildcards from within them:
This regex (/^(?=.*[A-Z])(?=.*\d).*$/) will return the entire password if it matches the criteria.
('a3sdasFf').match(/^(?=.*[A-Z])(?=.*\d).*$/);

Like below:
/(\d.*[A-Z])|([A-Z].*\d)/
To test a string matched or not:
var str = "abc32dQef";
var is_matched = /(\d.*[A-Z])|([A-Z].*\d)/.test(str);

Related

How to create a regex that checks the string contains specific pattern in javascript?

I have a requirement where I need to traverse through the string and get the first occurrence of a specific pattern like as follows,
i am a new **point**
On the occurrence of two consecutive character it must return true.
I must *not* be returned or*
The above pattern must return false.I tried to create regex following few links but the string.match method always returns null.
My code,
var getFormat = function(event) {
var element = document.getElementById('editor');
var startIndex = element.selectionStart;
var selectedText = element.value.slice(startIndex);
var regex = new RegExp(/(\b(?:([*])(?!\2{2}))+\b)/)
var stringMatch = selectedText.match(regex);
console.log('stringMatch', stringMatch);
}
<html>
<body>
<textarea onclick='getFormat(event);' rows='10' cols='10' id='editor'></textarea>
</body>
</html>
As I am new to regex I couldn't figure out where I am wrong.Could anyone help me out with this one?
On the occurrence of two consecutive character it must return true.
If I'm understanding you correctly. You just want to check if a string contains two consecutive characters, no matter which character. Then It should be enough doing:
(.)\1
Live Demo
This is of course assuming that it's literally any character. As in two consecutive whitespaces also being a valid match.
If you just need to check if there's two stars after each other. Then you don't really need regex at all.
s = "i am a new **point**";
if (s.indexOf("**") != -1)
// it's a match
If it's because you need the beginning and end of the two stars.
begin = s.indexOf("**");
end = s.indexOf("**", begin + 1);
Which you with regex could do like this:
((.)\2)(.*?)\1
Live Demo

change regex to match some words instead of all words containing PRP

This regex matches all characters between whitespace if the word contains PRP.
How can I get it to match all words, or characters in-between whitepsace, if they contain PRP, but not if they contain me in any case.
So match all words containing PRP, but not containing ME or me.
Here is the regex to match words containing PRP: \S*PRP\S*
You can use negative lookahead for this:
(?:^|\s)((?!\S*?(?:ME|me))\S*?PRP\S*)
Working Demo
PS: Use group #1 for your matched word.
Code:
var re = /(?:^|\s)((?!\S*?(?:ME|me))\S*?PRP\S*)/;
var s = 'word abcPRP def';
var m = s.match(re);
if (m) console.log(m[1]); //=> abcPRP
Instead of using complicated regular expressions which would be confusing for almost anyone who's reading it, why don't you break up your code into two sections, separating the words into an array and filtering out the results with stuff you don't want?
function prpnotme(w) {
var r = w.match(/\S+/g);
if(r == null)
return [];
var i=0;
while(i<r.length) {
if(!r[i].contains('PRP') || r[i].toLowerCase().contains('me'))
r.splice(i,1);
else
i++;
}
return r;
}
console.log(prpnotme('whattttttt ok')); // []
console.log(prpnotme('MELOLPRP PRPRP PRPthemeok PRPmhm')); // ['PRPRP', 'PRPmhm']
For a very good reason why this is important, imagine if you ever wanted to add more logic. You're much more likely to make a mistake when modifying complicated regex to make it even more complicated, and this way it's done with simple logic that make perfect sense when reading each predicate, no matter how much you add on.

Negated character not working as expected ? ^

I want to allow my users to enter a phone number and choose their own way of seperating the numbers (or not). So I came up with a regex:
var regex = /[^0-9 \/-\\\(\)\+]/;
In most cases it works fine, but there are some examples like #,:,; where it doesn't work as I would expect. Could someone give me some hint please ?
Here's an example of what I mean
testvar = '123#213';
var regex = /[^0-9 \/-\\\(\)\+]/;
if(regex.test(testvar) === true)
{ alert('Chars out of regex-range found'); } // won't fire!
There's a long way from / to \ if you meant it. And if not, you're missing a slash before the dash:
var regex = /[^0-9 \/\-\\\(\)\+]/;
A phone number only uses digits, I'd ignore the user format and just keep the digits
var phonenum=value.replace(/\D+/g,'');

getting contents of string between digits

have a regex problem :(
what i would like to do is to find out the contents between two or more numbers.
var string = "90+*-+80-+/*70"
im trying to edit the symbols in between so it only shows up the last symbol and not the ones before it. so trying to get the above variable to be turned into 90+80*70. although this is just an example i have no idea how to do this. the length of the numbers, how many "sets" of numbers and the length of the symbols in between could be anything.
many thanks,
Steve,
The trick is in matching '90+-+' and '80-+/' seperately, and selecting only the number and the last constant.
The expression for finding the a number followed by 1 or more non-numbers would be
\d+[^\d]+
To select the number and the last non-number, add parens:
(\d+)[^\d]*([^\d])
Finally add a /g to repeat the procedure for each match, and replace it with the 2 matched groups for each match:
js> '90+*-+80-+/*70'.replace(/(\d+)[^\d]*([^\d])/g, '$1$2');
90+80*70
js>
Or you can use lookahead assertion and simply remove all non-numerical characters which are not last: "90+*-+80-+/*70".replace(/[^0-9]+(?=[^0-9])/g,'');
You can use a regular expression to match the non-digits and a callback function to process the match and decide what to replace:
var test = "90+*-+80-+/*70";
var out = test.replace(/[^\d]+/g, function(str) {
return(str.substr(-1));
})
alert(out);
See it work here: http://jsfiddle.net/jfriend00/Tncya/
This works by using a regular expression to match sequences of non-digits and then replacing that sequence of non-digits with the last character in the matched sequence.
i would use this tutorial, first, then review this for javascript-specific regex questions.
This should do it -
var string = "90+*-+80-+/*70"
var result = '';
var arr = string.split(/(\d+)/)
for (i = 0; i < arr.length; i++) {
if (!isNaN(arr[i])) result = result + arr[i];
else result = result + arr[i].slice(arr[i].length - 1, arr[i].length);
}
alert(result);
Working demo - http://jsfiddle.net/ipr101/SA2pR/
Similar to #Arnout Engelen
var string = "90+*-+80-+/*70";
string = string.replace(/(\d+)[^\d]*([^\d])(?=\d+)/g, '$1$2');
This was my first thinking of how the RegEx should perform, it also looks ahead to make sure the non-digit pattern is followed by another digit, which is what the question asked for (between two numbers)
Similar to #jfriend00
var string = "90+*-+80-+/*70";
string = string.replace( /(\d+?)([^\d]+?)(?=\d+)/g
, function(){
return arguments[1] + arguments[2].substr(-1);
});
Instead of only matching on non-digits, it matches on non-digits between two numbers, which is what the question asked
Why would this be any better?
If your equation was embedded in a paragraph or string of text. Like:
This is a test where I want to clean up something like 90+*-+80-+/*70 and don't want to scrap the whole paragraph.
Result (Expected) :
This is a test where I want to clean up something like 90+80*70 and don't want to scrap the whole paragraph.
Why would this not be any better?
There is more pattern matching, which makes it theoretically slower (negligible)
It would fail if your paragraph had embedded numbers. Like:
This is a paragraph where Sally bought 4 eggs from the supermarket, but only 3 of them made it back in one piece.
Result (Unexpected):
This is a paragraph where Sally bought 4 3 of them made it back in one piece.

Regex to check a substring is having all numeric or not (in Java script)

I am using following code to check first four characters are alphabate or not.
var pattern = new RegExp('^[A-Z]{4}');
if (enteredID.match(pattern))
isValidAlphabates = true;
else {
isValidAlphabates = false;
This is working fine; Now I need to check the next 6 characters (of the entered text) need to be only numeric (0 to 9).
I ve the option to use substring or substr method to extract that part & use the regular experssion: ^[0-9]{6}.
But is there a better way to do it, without using the substring method here.
To clarify, the ^ means "at the start of the string". So you can combine your two regexes to say "start with four A-Z then have six 6 0-9."
var pattern = new RegExp('^[A-Z]{4}[0-9]{6}');
var pattern = new RegExp('^[A-Z]{4}[0-9]{6}');
var pattern = new RegExp('^[A-Z]{4}[0-9]{6}$');
I added $ that means that checked string must end there.
You can check the whole string at once
var pattern = new RegExp('^[A-Z]{4}[0-9]{6}');

Categories

Resources