Regexp for floating number - javascript

I found this regexp for validating floats. But I cant see how 2-1 will accepted. The below evaluates to true. I can't use parseFloat because I need to be able to accept "," instead of "." also. I wrote re2, same result though.
var re1 = new RegExp("^[-+]?[0-9]*\.?[0-9]+$");
console.log(re1.test("2-1"));
var re2 = new RegExp("^([0-9]+)\.([0-9]+)$");
console.log(re2.test("2-1"));

If you generate the regex using the constructor function, you have to to escape the backslash, i.e. \ becomes \\:
var re1 = new RegExp("^[-+]?[0-9]*\\.?[0-9]+$");
Another option is to use the literal syntax which doesn't require escaping:
var re1 = /^[-+]?[0-9]*\.?[0-9]+$/

Sometimes when you create a regex string, you even have to escape the backslash; this can of course be done with a backslash, so the final regex looks something like "\\.*", etc.
Doing this, I was able to get the correct results, as seen here:
var re1 = new RegExp("^[-+]?[0-9]*\\.?[0-9]+$");
console.log(re1.test("2-1"));
var re2 = new RegExp("^([0-9]+)\\.([0-9]+)$");
console.log(re2.test("2-1"));
console.log(re1.test("2.1"));
console.log(re2.test("2.1"));​

What about replacing a comma (",") with a period (".") and then using parseFloat?

Related

Turning a regex returned as a string from an API into a valid RegEx object in JavaScript

I'm fetching a regular expression from an external API, and it comes back as a string. I want to use the regex for address validation, but I can't seem to properly escape the unwanted characters after calling new RegExp() on the string.
Here's the regex I want to use:
console.log(regexFromAPI);
Output
/((\W|^)box\s+(#\s*)?\d+|post\s+office|(\W|^)p\.?\s*o\.?\s+(#\s*)?\d+)/i
However, I can't use that -- I need it to actually be a regex first.
If I do, for example:
const pattern = new RegExp(regexFromAPI);
and then:
console.log(pattern);
I get the following:
Output
//((W|^)boxs+(#s*)?d+|posts+office|(W|^)p.?s*o.?s+(#s*)?d+)/i/
My question is... why is this happening, and how can I avoid it? I want to use my string literal as a regex.
Thanks in advance.
The RegExp constructor does not expect a string with / delimiters, nor with options past the final /. If you do that, the pattern generated from calling new RegExp with it will result in one that matches a string which starts with a literal forward slash /, and ends with a forward slash / followed by the flag characters (here, i).
Instead, you should pass the pattern string without / delimiters, and pass the flags as the second argument - you can extract these easily by using another regular expression:
const fullPatternStr = String.raw`/((\W|^)box\s+(#\s*)?\d+|post\s+office|(\W|^)p\.?\s*o\.?\s+(#\s*)?\d+)/i`;
const [, pattern, flags] = fullPatternStr.match(/\/(.*)\/([a-z]*)/);
const regex = new RegExp(pattern, flags);
console.log(regex);
Take off the slashes and flags, then reconstruct it:
const str = String.raw`/((\W|^)box\s+(#\s*)?\d+|post\s+office|(\W|^)p\.?\s*o\.?\s+(#\s*)?\d+)/i`;
let regexBody = str.slice(1, str.lastIndexOf("/"));
let flags = str.split("/")[str.split("/").length - 1];
let regex = new RegExp(regexBody, flags);
console.log(regex);

regex for serial number in javascript

var serialNumber = $('#SerialNumber').val();
var serialNumberPattern = new RegExp('^[\s\da-zA-z\-.]+$');
if (!serialNumberPattern.test(serialNumber)) {
}
Above is the code I am using to validate a serial number which has alphanumeric characters, dots (.), dashes (-), and slashes (/) in it but somehow it's not working. Where am I going wrong? Please help.
When you're passing regex to RegExp constructor which uses " as regex delimiter, you have to escape all the backslashes one more time. Or otherwise it would be treated as an escape sequence.
var serialNumberPattern = new RegExp("^[\\s\\da-zA-Z.-]+$");
alphanumeric,dot(.),Dash(-),Slash(/) in it.
var serialNumberPattern = new RegExp("^[\\da-zA-Z./-]+$");
Just use /^[\s\da-zA-Z\-.\/]+$/, it's simple and works just fine.
You should only use the RegExp constructor when parts of the expression use a variable. This is not true in your case and just adds additional confusion.
document.write(/^[\s\da-zA-Z\-.\/]+$/.test('23 43-89'))

Javascript - Why is my RegEx for dd.mm.yyyy - dd.mm.yyyy not working?

I have written following code:
var date_regex = new RegExp("\d{2}[./-]\d{2}[./-]\d{4}", "gi");
var period = "27.03.2014 - 24.04.2014";
console.log(date_regex.exec(period));
I get console log : null.
I checked my code on this site and it says valid. What is wrong? Thanks for help!
\d{2}[./-]\d{2}[./-]\d{4}
Debuggex Demo of my RegEx
You need to escape your backslashes:
var date_regex = new RegExp("\\d{2}[./-]\\d{2}[./-]\\d{4}", "gi");
Just as a side note, you can avoid matching strings with mismatched delimiters such as "27.01-1444" by capturing the first delimiter and matching the same one for the second delimiter via \1:
var date_regex = new RegExp("\\d{2}([./-])\\d{2}\\1\\d{4}", "gi");
You are creating your regex from a string, so you need to escape the backslashes:
var date_regex = new RegExp("\\d{2}[./-]\\d{2}[./-]\\d{4}", "gi");
Or it's less complicated to use a regex literal:
var date_regex = /\d{2}[./-]\d{2}[./-]\d{4}/gi;
When creating a regular expression object (as opposed to the literal) with a string, you need to double escape slashes:
var date_regex = new RegExp("\\d{2}[./-]\\d{2}[./-]\\d{4}", "gi");
You'll discover that logging date_regex results in /d{2}[./-]d{2}[./-]d{4}/gi - not what we wanted!
However, you only need to use a string under certain conditions:
The regex involves a variable
The regex is formed in a loop (string prevents recompilation)
Thus, you'd be better off using a literal in this case:
var date_regex = /\d{2}[./-]\d{2}[./-]\d{4}/gi;
See MDN for more details on creating RegExp objects.
Combine the given answers and use .match to return all matches in an array.
var date_regex = /\d{2}[./-]\d{2}[./-]\d{4}/gi;
var range = "27.03.2014 - 24.04.2014";
console.log( range.match(date_regex) ); // [ "27.03.2014", "24.04.2014" ]

javascript regex to require at least one special character

I've seen plenty of regex examples that will not allow any special characters. I need one that requires at least one special character.
I'm looking at a C# regex
var regexItem = new Regex("^[a-zA-Z0-9 ]*$");
Can this be converted to use with javascript? Do I need to escape any of the characters?
Based an example I have built this so far:
var regex = "^[a-zA-Z0-9 ]*$";
//Must have one special character
if (regex.exec(resetPassword)) {
isValid = false;
$('#vsResetPassword').append('Password must contain at least 1 special character.');
}
Can someone please identify my error, or guide me down a more efficient path? The error I'm currently getting is that regex has no 'exec' method
Your problem is that "^[a-zA-Z0-9 ]*$" is a string, and you need a regex:
var regex = /^[a-zA-Z0-9 ]*$/; // one way
var regex = new RegExp("^[a-zA-Z0-9 ]*$"); // another way
[more information]
Other than that, your code looks fine.
In javascript, regexs are formatted like this:
/^[a-zA-Z0-9 ]*$/
Note that there are no quotation marks and instead you use forward slashes at the beginning and end.
In javascript, you can create a regular expression object two ways.
1) You can use the constructor method with the RegExp object (note the different spelling than what you were using):
var regexItem = new RegExp("^[a-zA-Z0-9 ]*$");
2) You can use the literal syntax built into the language:
var regexItem = /^[a-zA-Z0-9 ]*$/;
The advantage of the second is that you only have to escape a forward slash, you don't have to worry about quotes. The advantage of the first is that you can programmatically construct a string from various parts and then pass it to the RegExp constructor.
Further, the optional flags for the regular expression are passed like this in the two forms:
var regexItem = new RegExp("^[A-Z0-9 ]*$", "i");
var regexItem = /^[A-Z0-9 ]*$/i;
In javascript, it seems to be a more common convention to the user /regex/ method that is built into the parser unless you are dynamically constructing a string or the flags.

RegExp.test not working?

I am trying to validate year using Regex.test in javascript, but no able to figure out why its returning false.
var regEx = new RegExp("^(19|20)[\d]{2,2}$");
regEx.test(inputValue) returns false for input value 1981, 2007
Thanks
As you're creating a RegExp object using a string expression, you need to double the backslashes so they escape properly. Also [\d]{2,2} can be simplified to \d\d:
var regEx = new RegExp("^(19|20)\\d\\d$");
Or better yet use a regex literal to avoid doubling backslashes:
var regEx = /^(19|20)\d\d$/;
Found the REAL issue:
Change your declaration to remove quotes:
var regEx = new RegExp(/^(19|20)[\d]{2,2}$/);
Do you mean
var inputValue = "1981, 2007";
If so, this will fail because the pattern is not matched due to the start string (^) and end string ($) characters.
If you want to capture both years, remove these characters from your pattern and do a global match (with /g)
var regEx = new RegExp(/(?:19|20)\d{2}/g);
var inputValue = "1981, 2007";
var matches = inputValue.match(regEx);
matches will be an array containing all matches.
I've noticed, for reasons I can't explain, sometimes you have to have two \\ in front of the d.
so try [\\d] and see if that helps.

Categories