javascript regular expression not working - javascript

I am trying to validate a textbox to ensure that a URL is written inside (minus the "http://" part). Here is my code:
var isUrl;
var regex = new RegExp("^(?!http)(www\.)?(([a-z])+\.[a-z]{2,}(\.[a-z]{2,})?)");
var siteUrl = e.target.value;
if (siteUrl.match(regex)) {
isUrl = true;
}
else {
isUrl = false;
}
So my regular expression is ^(?!http)(www\.)?(([a-z])+\.[a-z]{2,}(\.[a-z]{2,})?).
I was under the impression that this would do the following:
NOT match anything beginning with http.. which it does correctly
Allow an optional www. at the start
Accept 1 or more characters from a-z to be typed in
Accept a dot after those characters
Accept 2 or more characters following the dot, and
Allow an optional dot followed by two or more characters again.
In practice, the textbox accepts strings like "ashdiguasdf" and "aksjdnfa:://',~" which it should not do. Can anyone explain why?

The main problem is that you're using the \ character in a quoted string, which javascript will interpret as the start of a "control character" (such as \n for a newline, etc).
One option is to escape it by replacing \ with \\.
But the easiest solution is to use the following format...
var regex = new RegExp(/^(?!http)(www\.)?(([a-z])+\.[a-z]{2,}(\.[a-z]{2,})?)/);
This also allows you to make it case insensitive (if you wish) by using the i character at the end, like this...
var regex = new RegExp(/^(?!http)(www\.)?(([a-z])+\.[a-z]{2,}(\.[a-z]{2,})?)/i);
As an extra bit, you're using more capture groups than really necessary. Your expression could also be written like this with the same result...
^(?!http)(?:www\.)?[a-z]+(?:\.[a-z]{2,}){1,2}

Related

regular expression for validating fields

Validations i'm trying :
regular expression of : 9999.99 and no spaces (0009.99 it should convert 9.99
Edit :
var regex = '(?!0)\d+(?:\.\d+)?$';
function getValue() {
// passing value 0009.99 and 0009.00 and 100
return document.getElementById("myinput").value;
}
function test() {
alert(regex.test(getValue()));
}
function match() {
alert(getValue().match(regex));
}
Your first and second seems to Work just fine, the third can be achieved with the following regex:
/(?!0)\d+\.\d+$/
It starts by looking forward for zeros (skipping them), then it matches any number of digits followed by a dot and more digits. If you want the digits to be optional you can replace the plus '+' with a star '*'.
Edit:
If you want to allow integers, you can use this regex:
/(?!0)\d+(?:\.\d+)?$/
That makes the dot and the digits after that optional.
BTW: Your jsfiddle does not help in answering.
Edit2:
To create a Regex using quotes you must use the following syntax:
var regex = new RegExp('(?!0)\d+(?:\.\d+)?$');
Edit3:
I forgot to mention, you need to double escape backslashes, it should be:
var regex = new RegExp('(?!0)\\d+(?:\\.\\d+)?$');
Now it should Work directly in your code.

Regex to allow certain special characters - escape issue

I've working on a javascript regex that I intend to use with the jquery validate plugin (I'll add this as an additional method). It must (among other rules):
test if at least one of the following special characters is entered:
!, ", #, $, %, &, ', (, ), *, +,-, .,/, :, ;, <, =, >, ?, #, [, \, ], ^, _, `, {, |, }, ~
not allow 3 consecutive identical characters:
passed:
aa
99
++
not passed:
aaa
999
+++
The problem with my regex is that is having problem with these mentioned rules:
I think the issue is related to escaping and I've tried escaping + and - to no avail. Can anyone help! This is my regex: http://regexr.com/3ack3
This is one of those requirements where you can really simplify your life by using multiple regexes, rather than trying to cram all the logic into one complex regex with many assertions. Here's some JavaScript that implements your requirement:
var specialCharRegex = /[!"#$%&'()*+.\/:;<=>?#\[\\\]^_`{|}~-]/;
var threeConsecutiveRegex = /(.)\1\1/;
var input = prompt();
if (specialCharRegex.test(input) && !threeConsecutiveRegex.test(input)) {
alert('passed');
} else {
alert('failed');
} // end if
http://jsfiddle.net/t8609xv2/
Some notes on the trickier points:
inside the bracket expression, the following four special characters had to be backslash-escaped: /[\]. (Forward slash because it delimits the regex, backslash because it's the escape character, and the brackets because they delimit the bracket expression.)
inside the bracket expression, the dash had to be moved to the end, because otherwise it would likely specify a character range. When at the end, it never specifies a range, so it's always safer to put it there.
This modular approach also benefits maintainability, as you will more easily be able to make changes (modify/add/remove regexes, or change the if-test logic) at a later point in time.
Another benefit is that you could test each regex independently, which could allow you to provide a more accurate error message to the user, as opposed to just saying something like "invalid password".
Edit: Here's how you can whitelist the chars that are accepted in the input:
var specialCharRegex = /[!"#$%&'()*+.\/:;<=>?#\[\\\]^_`{|}~-]/;
var threeConsecutiveRegex = /(.)\1\1/;
var nonWhitelistCharRegex = /[^a-zA-Z0-9!"#$%&'()*+.\/:;<=>?#\[\\\]^_`{|}~-]/;
var input = prompt();
if (specialCharRegex.test(input) && !threeConsecutiveRegex.test(input) && !nonWhitelistCharRegex.test(input)) {
alert('passed');
} else {
alert('failed');
} // end if
http://jsfiddle.net/t8609xv2/2/
^(?=.*[!"#$%&'()*+,,\/:;<=>?#\[\]^_`{|}~-])(?!.*(.)\1\1).*$
Try this.See demo.
https://regex101.com/r/wX9fR1/10
You need a positive lookahead to check for special characters.
And
A negative lookahead to check if a character is is there 3 times.
You can use this regex:
^(?!.*?(.)\1{2})(?=[^a-z]*[a-z])(?=[^A-Z]*[A-Z])(?=\D*\d)(?=.*?[!##$%^&*()_=\[\]{};':"\\|,.<>\/?+-]).{8,20}$
RegEx Demo
You might be able to shorten it using:
^(?!.*?(.)\1{2})(?=[^a-z]*[a-z])(?=[^A-Z]*[A-Z])(?=\D*\d)(?=.*?[\W_]).{8,20}$
i.e. using non-word property \W instead of listing each and every special character.

Regex with numerics and dashes only

I am facing an issue in JavaScript form validation. I have to store number in this format 1-74347064527
I have tried these regular expressions but not worked properly:
var srNo =/^[-0-9]*$/;
var srNo = /^[0-9]+(-[0-9]+)+$/;
var srNo=/^([0-9]+-)*[0-9]+$/;
Suggest some regex for this.
Kind regards.
This should work unless you have additional constraints:
var srNo = /^\d+-\d+$/;
If you prefer the [0-9] syntax:
var srNo = /^[0-9]+-[0-9]+$/;
When in a character class ([ ]), dash ( - ) has a special meaning in regular expressions - it means "range", eg. a-z means from 'a' to 'z'. You're not escaping it, so your RegExps are not even correct (at least not in every language).
Update: It appears, that this syntax is correct when dash is not surrounded by other characters (when it's placed at the beginning or end of the character class). Sorry for confusion.
Try this instead:
/^\d\-\d+$/
It matches strings that begin with one digit, followed by a dash, and then by one or more digits.
var regex = /^\d{1}-?\d{11}$/g
window.alert(regex.test('1-74347064527'));

Matching "{CHARACTERS}" using Javascript RegExp

I'm really struggling with the Javascript version of Regular Expression matching, despite knowing how to do it in other languages like C# and PHP.
I wish to match {ANYCHARACTERS}.
It must have:
a { at the start
a } at the end
1 or more characters between (any characters, symbols etc.)
So far I have the following:
<script type="text/javascript">
// The string that I want to perform a match on
var str = "{ASTRINGINHERE£$%^&*éáó}";
// Mt Matching expression
var patt1 = ^/{(.*){1,*}/}$/i;
// Write the matched result
document.write(str.match(patt1));
</script>
As written, your current pattern should result in a javascript syntax error. Here are the problems I see:
You have your ^ character outside the actual regular expression.
You have two regular expression ending characters (/).
See #kopischke's answer on why I removed the {1,} portion.
This should resolve your issues:
/^{(.+)}$/i
The string start / string end codes belong inside the regex. Also, your repetition code is unnecessarily complex. Finally, there is no need to indicate case independence when you match any character. This should do:
patt1 = /^{.+}$/

Javascript: String replace problem

I've got a string which contains q="AWORD" and I want to replace q="AWORD" with q="THEWORD". However, I don't know what AWORD is.. is it possible to combine a string and a regex to allow me to replace the parameter without knowing it's value? This is what I've got thus far...
globalparam.replace('q="/+./"', 'q="AWORD"');
What you have is just a string, not a regular expression. I think this is what you want:
globalparam.replace(/q=".+?"/, 'q="THEWORD"');
I don't know how you got the idea why you have to "combine" a string and a regular expression, but a regex does not need to exist of wildcards only. A regex is like a pattern that can contain wildcards but otherwise will try to match the exact characters given.
The expression shown above works as follows:
q=": Match the characters q, = and ".
.+?": Match any character (.) up to (and including) the next ". There must be at least one character (+) and the match is non-greedy (?), meaning it tries to match as few characters as possible. Otherwise, if you used .+", it would match all characters up to the last quotation mark in the string.
Learn more about regular expressions.
Felix's answer will give you the solution, but if you actually want to construct a regular expression using a string you can do it this way:
var fullstring = 'q="AWORD"';
var sampleStrToFind = 'AWORD';
var mat = 'q="'+sampleStrToFind+'"';
var re = new RegExp(mat);
var newstr = fullstring.replace(re,'q="THEWORD"');
alert(newstr);
mat = the regex you are building, combining strings or whatever is needed.
re = RegExp constructor, if you wanted to do global, case sensitivity, etc do it here.
The last line is string.replace(RegExp,replacement);

Categories