I am trying to use RegExp validation for a number that can have up to 5 numbers followed up one option decimal place. Like 48293 or 23.4 are good. 99.99 or 453543 are not. I wrote the following function:
function validateLoad(load_value) {
var matchValue = new RegExp('[0-9]{1,5}(\.[0-9]{1})?')
return matchValue.test(load_value)
}
However, this seems to return true for all numerical values, can anyone tell me how to fix this?
You need to use anchors to make sure the entire string (and not just a substring) is matched by the regex. Also, don't forget to double the backslashes if you construct the regex from a string (and drop the {1}, it's a no-op):
var matchValue = new RegExp('^[0-9]{1,5}(\\.[0-9])?$');
Using literal notation would avoid to escape backslashes :
function validateLoad(load_value) {
return /^\d{1,5}(\.\d)?$/.test(load_value)
}
Related
I have a structure of string, I need a regular expression that only picks up the numbers from the structure, and also the expression should report if the structure deviates from the mentioned rule (suppose if I missed any comma or full stop or braces etc)
The structure is - {'telugu':['69492','69493','69494'],'kannada':['72224']}
The regular expression I've tried is /\[(.*?)\]/g;
The above expression is working fine for picking only numbers from the given input, but it's not reporting for the missing of any comma, fullstop or braces etc.
var contentids = {'telugu':['69492','69493','69494'],'kannada':['72224']};
var pattern = /\[(.*?)\]/g;
while ((match = pattern.exec(contentids)) != null) {
var arrayContentids2 = new Array();
arrayContentids2 = match[1].split(",");
}
I am fetching only the numbers from the given input,but I need a validation of missing commas, fullstop, braces etc from the input.
To get all the numbers you can use a RegEx like this /\'(\d+)\'|\"(\d+)\"/g. The second part is only for numbers inside " instead of ', so you can remove this if you want.
To check the balance of braces i would use a simple counting loop and move through the input. I don't think that RegEx are the right tool for this job.
To search missing commas you could use the RegEx /([\'\"]\s*[\'\"])/g and /([\[\(\{]\d+)/g to find the tow errors in
{'telugu':['69492','69493','69494'],'kannada':[72224''72224']}
Hope this will help you
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'))
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.
I am trying to write some Javascript to hide some elements that contain only carriage returns. I appreciate that the correct way to solve this problem would be to stop these elements being created, but unfortunately that is not possible in this instance. I am trying to user a regular expression to search for the unwanted elements but am not having much luck. The function I have written is as follows:
function HideEmptyP()
{
var patt = (\\r)
for(var i = 0;i<desc[i].length;i++);
{
var desc[i] = document.getElementsByClassName('sitspagedesc');
var result[i] = patt.test(desc[i]);
if (result[i] == true)
{
desc[i].style.display='none';
}
else
{
alert("No Match!");
}
}
The error I'm getting in the Web Console is 'Syntax Error: Illegal Character'.
Grateful for any ideas on how to solve this.
Thanks in advance.
I am trying to write some Javascript to hide some elements that contain only carriage returns.
There's no need for a regular expression for that, just compare the element's innerHTML property to "\\r", e.g.:
if (demo[i].innerHTML === "\\r") {
// Remove it
}
But beware that some browsers may transform a single carriage return. You might want to check for "\\r", "\\n", and just a space. To do that, you might want to use a regular expression.
Your regular expression literal ((\\r)) is just completely invalid, it's worth reading up on them to learn the correct syntax. To write a regular expression literal in JavaScript, you use / as the delimiter. So: /\\r/. To test that a string contains only \r, \n, or space, you can use /^[\r\n ]+$/ (which requires there be at least one character that matches, and uses ^ to indicate start-of-string, and $ to indicate end-of-string):
if (demo[i].innerHTML.match(/^[\r\n ]+$/) {
// Remove it
}
The reason you are getting Syntax error is because the declaration
var patt = (\r)
is incorrect it should be somethign like var patt = '\r';
Also the whole for loop is wrong.
You should define demo before you start the for loop not inside it, and result need not be an array but just a normal variable
Your litteral seems odd.
Try var patt = /\r/;
var patt=/\n/gi
should work.
extra i flag to denote case insensitive.
g for global search.
I have several Javascript strings (using jQuery). All of them follow the same pattern, starting with 'ajax-', and ending with a name. For instance 'ajax-first', 'ajax-last', 'ajax-email', etc.
How can I make a regex to only grab the string after 'ajax-'?
So instead of 'ajax-email', I want just 'email'.
You don't need RegEx for this. If your prefix is always "ajax-" then you just can do this:
var name = string.substring(5);
Given a comment you made on another user's post, try the following:
var $li = jQuery(this).parents('li').get(0);
var ajaxName = $li.className.match(/(?:^|\s)ajax-(.*?)(?:$|\s)/)[1];
Demo can be found here
Below kept for reference only
var ajaxName = 'ajax-first'.match(/(\w+)$/)[0];
alert(ajaxName);
Use the \w (word) pattern and bind it to the end of the string. This will force a grab of everything past the last hyphen (assuming the value consists of only [upper/lower]case letters, numbers or an underscore).
The non-regex approach could also use the String.split method, coupled with Array.pop.
var parts = 'ajax-first'.split('-');
var ajaxName = parts.pop();
alert(ajaxName);
you can try to replace ajax- with ""
I like the split method #Brad Christie mentions, but I would just do
function getLastPart(str,delimiter) {
return str.split(delimiter)[1];
}
This works if you will always have only two-part strings separated by a hyphen. If you wanted to generalize it for any particular piece of a multiple-hyphenated string, you would need to write a more involved function that included an index, but then you'd have to check for out of bounds errors, etc.