javascript pattern matching - javascript

matchArray becomes null for input like asklas#(((# How do I correct this behavior? I only want to allow characters and numbers..
function validateName(name) {
debug(name);
var namePat = /^(\[A-Za-z0-9]*)$/ ;
var matchArray = name.match(namePat);
if (!matchArray){
debug ("Invalid name,", name );
return false;
}
return true;
}

There is one erroneous backslash in your regex. It should be
var namePat = /^[A-Za-z0-9]*$/;
(and you don't need the capturing parentheses, either).

Not sure what you want in this case... if you want a boolean output, use .test:
namePat.test(name)
... but null will work for your test (!matchArray) just fine.
It does seem like you have a typo in your regular expression - you'll want to get rid of the backslash before the opening bracket...

Related

Regular expression not supporting line skipping \n

I'm trying to find the right regular expression for a number with a line skip at the end ( \n ) but every time it's not working.
My regular expression is /^\d+(\n)$/.
EDIT : The text area contains :
22\n
33
Here's my code ( I'm trying to validate what's in the textarea and it's only numbers going there with \n at the end of each lines ) :
function valideChamp()
{
var rExp1 = /^\d+(\n)$/;
var aChamps = document.querySelector("textarea").value;
if (rExp1.test(aChamps.value)==true){
alert("Valide")
}
else {
alert("Invalide")
return false;
}
}
If you want to check for any line containing only a number on it, you can use:
/(^|\n)\d+(\r?\n)/
If you just want to check that there's only a number, and then a newline, and nothing else:
/^\d+(\r?\n)$/
(which is what you were checking for, but that's an odd input pattern.)
If you want to make sure textarea ONLY has lines that are numbers, it might be simpler to check that string.replace(/[0-9\r\n]/g, '') == ''. This will confirm if it contains only numbers and newlines.
Remove ".value"
from this line:
if (rExp1.test(aChamps.value)==true){
You're using $ and \n together which is slightly redundant. Try
/\d+$/gm
where g = global flag and m = multiline flag. Note this will match multiple lines.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp

match doesnt work after adding delimiters

I'm using a simple regex to test a string, it works just fine until I add delimiters to it. Can someone please explain why is this happening, do I have to add the delimiters in every regex?
var Cont = $("#input").val(),
cCheck = "^[0-9a-zA-Z\-\u0590-\u05FF !?.,]+$", //this one works
cCheckB = "/^[0-9a-zA-Z\-\u0590-\u05FF !?.,]+$/"; //this one doesnt
if(!Cont.match(cCheck)){
alert("bad"); return false;
}
else{
alert("good"); return false;
}
You do not quote a regexp in JavaScript when using delimiters.
var cCheckB = /^[0-9a-zA-Z\-\u0590-\u05FF !?.,]+$/;
I suspect you are trying to use a regular expression literal, which in javascript is delimited with '/'. However, if you use that you don't want the quotes around it.
cCheck = /^[0-9a-zA-Z\-\u0590-\u05FF !?.,]+$/

Javascript Regex doesn't match with my String

I have the following String :
var resultLine= "[UT] - GSM incoming call : STEP 1 - Simulate reception from server (1)Rerun3713 msAssertion ok"
And the following code which is responsible to check of the String matched with the Regex :
var resultRE = /^([ \w-]*: )?(.+) \((\d+), (\d+), (\d+)\)Rerun/;
var resultMatch = resultLine.match(resultRE);
if (resultMatch) {
return true;
} else {
return false;
}
In this case, i have an error in my Regex because i always get "false".
Where is my mistake ?
I would recommend the following pattern based on what it appears you are looking for:
var resultRE = /^([\[ \w\]-]*: )(.+) \(([0-9, ]*)\)Rerun(.*)$/
This should force all capture groups to exist, even if they are empty, and will allow for multiple numbers before Rerun as you seem to expect.
This matches nothing in your string
([ \w-]*: )?
Since it was optional, that doesn't matter because it gets caught by the all inclusive
(.+)
If you were trying to match the [UT] part with it's separator, it would look something like this
(\[\w+\][\s\-]*)?
As noted in the comments, you only have one number in parentheses but your regex requires three sets of them, separated by commas. This will allow any number of numbers, separated by commas indefinitely (I don't know if there's a limit or not).
\((\d+,\s)*(\d+)\)
If you need something more specific, you'll have to be more specific about what template your matching, not a specific case. But the best I can figure with what you've provided is
^(\[\w\][\s\-]*)?(.+)\((\d+,\w)*(\d+)\)Rerun
var resultRE = /\((\d+)(?:, (\d+))?(?:, (\d+))?\)Rerun/;
if (resultRE.test(resultLine)) {
var num1 = RegExp.$1,
num2 = RegExp.$2,
num3 = RegExp.$3;
}

Validation on onKeyUp

I need to do validation onkeyup and onsubmit.
I have field called CVV which accepts 3 or 4 digits numbers, so i'm using '^(d){3,4}$'.
This pattern works properly when i did in onsubmit function, but in onkeyup function i get always false even i enter 3 digits number.
<input type="text" onkeyup="callonkeyup(this,'First Name','^(d){3,4}$')" value="First Name">
function callonkeyup(tag,defaultValue,pattern){
var isValidate = validate(pattern,trim(tag.value),defaultValue);
console.log("==isValidate=="+isValidate+"==tag.value=="+tag.value+"===pattern==="+pattern);
}
function validate(pattern,value,defaultVal){
var returnValue = false;
if(value && value != defaultVal){
while(pattern.indexOf('\\\\') != -1) {
pattern = pattern.replace('\\\\', "\\");
}
var testPattern = new RegExp(pattern,"");
if (testPattern.test(value)){
returnValue = true;
}else{
returnValue = false;
}
}
return returnValue;
}
function trim(value){
return value.toString().replace(/^\s+|\s+$/g,'');
}
Working DEMO
You need to escape back slash (\) so your regular expression should be ^\\d{3,4}$ instead ^(d){3,4}$
You need to add a \ in front of the d, without it the d is represented as the character d and not a numeric value. Here's the expression you should use ^\d{3,4}$.
EDIT
The first part was on track, but I missed that you were passing the pattern as a string to another function. If you were to run new RegExp('^\d{3,4}$', "") it would work, but because it was being passed through a function, the \ character was being removed. In order to pass a string with a backslash in it, you need to escape the slash with another back slash like so \\. This means your new expression should be ^\\d{3,4}$.
When developing regular expression I usually use something like http://regexpal.com/ to help test them. Keep in mind that for this one you would have to check the ^$ match at line breaks (m) box for it to match multiple tests on multiple lines

Regex to match carriage return in Javascript

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.

Categories