I am holding in a field the validation format that I would need.
I need to convert different ## into a regex validation.
Is there a simple replace that can do this for me.
for example, i need to validate the account number.
sometimes it might need to be ###-###, or I'll get ####### or ##-####.
depending what is in the id="validationrule" field
I'm looking for
regex = $('#validationrule').replace("#", "[0/9]");
It also has to take into consideration that sometimes there is a dash in there.
Your question seems to be about creating regexes from a string variable (which you get from an input field that specifies the validation format).
"###-###" might turn into /^\d{3}\-\d{3}$/
"#######" might turn into /^\d{7}$/
If your validation format is built from the 2 characters # and -, this would work:
function createValidationRegEx(format){
format = format
.replace(/[^#\-]/g, '') //remove other chars
.replace(/#/g, '\\d') //convert # to \d
.replace(/\-/g, '\\-'); //convert - to \-
return new RegExp('^' + format + '$', 'g');
}
//create regexes
var format1 = createValidationRegEx('###-###');
var format2 = createValidationRegEx('#######');
//test regexes
console.log(format1.test('123-456')); // true
console.log(format2.test('123-456')); // false
console.log(format1.test('1234567')); // false
console.log(format2.test('1234567')); // true
Please note that you need to pay attention to which characters needs to be escaped when creating regexes from strings. This answer provides more details about how to solve this more generally, if you want to build more complex solutions.
If you are trying to replace the .value of an <input> element you can use .val(function), return replacement string from .replace() inside of function, chain .val() to assign result to regex. Use RegExp constructor with g flag to replace all matches of the RegExp supplied to .replace() to match characters against at string.
var regex = $("#validationrule").val(function(_, val) {
return val.replace("#", "[0/9]");
}).val();
console.log(regex);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
</script>
<input id="validationrule" value="#">
Related
I have a question related to formatting strings.
User should parse a string in the Format XX:XX.
if the string parsed by user is in the format XX:XX i need to return true,
else false:
app.post('/test', (req, res) => {
if (req.body.time is in the format of XX:XX) {
return true
} else {
return false
}
});
You can use the RegExp.test function for this kind of thing.
Here is an example:
var condition = /^[a-zA-Z]{2}:[a-zA-Z]{2}$/.test("XX:XX");
console.log("Condition: ", condition);
The regex that I've used in this case check if the string is composed from two upper or lower case letters fallowed by a colon and other two such letters.
Based on your edits it seems that you're trying to check if a string represents an hour and minute value, if that is the case, a regex like this will be more appropriate /^\d{2}:\d{2}$/. This regex checks if the string is composed of 2 numbers fallowed by a colon and another 2 numbers.
The tool you're looking for is called Regular Expressions.
It is globally supported in almost every development platform, which makes it extremely convenient to use.
I would recommend this website for working out your regular expressions.
/^[a-zA-Z]{2}:[a-zA-Z]{2}&/g is an example of a Regular Expression that will take any pattern of:
[a-zA-Z]{2} - two characters from the sets a-z and A-Z.
Followed by :
Followed by the same first argument. Essentially, validating the pattern XX:XX. Of course, you can manipulate it as to what you want to allow for X.
^ marks the beginning of a string and $ marks the end of it, so ASD:AS would not work even though it contains the described pattern.
try using regex
var str = "12:aa";
var patt = new RegExp("^([a-zA-Z]|[0-9]){2}:([a-zA-Z]|[0-9]){2}$");
var res = patt.test(str);
if(res){ //if true
//do something
}
else{}
i tried to replace a string, provided the string regex with a value that has $ in the end.
Can anyone tell me what is happening in
Looking into mdn string replace docs, i found it is expected.
But what should one do he want to ignore this.
Means i want the replacing value should get as it is replaced, with 4 $s here.
You need to double the dollars in the replacement pattern as $$ are actually $.
.replace(/{{one}}/g, '000$$$$$$$$')
See String#replace help:
Pattern Inserts
$$ Inserts a "$".
If a user types $ in the replacement (that is, in case it is user-defined) you can just double it:
var ptrn = "{{one}}"; // regex pattern from user input
var repl = "000$$$$"; // replacement from user input
var rx = RegExp(ptrn, "g"); // building a dynamic regex
document.write("pp{{one}}pp".replace(rx, repl.replace(/\$/g, '$$$$')));
// ^--- doubling $s-----^
This is my string converted into javascript object.
{"text" : "Must consist of alphabetical characters and spaces only", regexp:"/^[a-z\\s]+$/i"}
I need regexp to use it for validation but it won’t work because of the double quotes and \s escape sequence.
To make it work the value of regexp must be {"text" : "Must consist of alphabetical characters and spaces only", regexp : /^[a-z\s]+$/i}.
I also used this new RegExp(object.regexp) and any other way I can possibly think but with no luck at all.
Any help is appreciated!
Try split-ing out the part that you want, before putting it into the new RegExp constructor:
var regexVariable = new RegExp(object.regexp.split("/")[1]);
That will trim off the string representation of the regex "boundaries", as well as the "i" flag, and leave you with just the "guts" of the regex.
Pushing the result of that to the console results in the following regex: /^[a-z\s]+$/
Edit:
Not sure if you want to "read" the case insensitivity from the value in the object or not, but, if you do, you can expand the use of the split a little more to get any flags included automatically:
var aRegexParts = object.regexp.split("/");
var regexVariable = new RegExp(aRegexParts[1], aRegexParts[2]);
Logging that in the console results in the first regex that I posted, but with the addition of the "i" flag: /^[a-z\s]+$/i
Borrowing the example #RoryMcCrossan made, you can use a regular expression to parse your regular expression.
var object = {
"text": "Must consist of alphabetical characters and spaces only",
"regexp": "/^[a-z\\s]+$/i"
}
// parse out the main regex and any additional flags.
var extracted_regex = object.regexp.match(/\/(.*?)\/([ig]+)?/);
var re = new RegExp(extracted_regex[1], extracted_regex[2]);
// don't use document.write in production! this is just so that it's
// easier to see the values in stackoverflow's editor.
document.write('<b>regular expression:</b> ' + re + '<br>');
document.write('<b>string:</b> ' + object.text + '<br>');
document.write('<b>evaluation:</b> ' + re.test(object.text));
not used regex in Java but the regular expression itself should look something like :
"^([aA-zZ] | \s)*$"
If Java uses regular expression as I am used to them [a-z] will only capture lowercase characters
Hope this helps even if it's just a little (would add this as a comment instead of answer but need 50 rep)
I'm such a newb in regex, but still...
I based my test on this post.
I have this simple regex :
^-?([1]?[1-7][1-9]|[1]?[1-8][0]|[1-9]?[0-9])\.{1}\d{1,6}
In Debuggex, if I test it with 88.5 for example, it matches.
In my JS file, I have :
var lonRegex = new RegExp("^-?([1-8]?[1-9]|[1-9]0)\.{1}\d{1,6}");
var check = lonRegex.test(88.5); // hardcoded for demo
console.log(check) // output false
I can't guess why it's always returning me false, whatever the value is a number or a string like "88.5".
You will need to escape some characters when creating a RegExp object from a string. From MDN:
When using the constructor function, the normal string escape rules (preceding special characters with \ when included in a string) are necessary.
In your case, this will work (note the double \ for \d and .):
var lonRegex = new RegExp("^-?([1-8]?[1-9]|[1-9]0)\\.{1}\\d{1,6}");
var check = lonRegex.test(88.5); // hardcoded for demo
console.log(check) // output true
My objective is to replace all characters which are not dash (-) or not number or not letters in any language in a string.All of the #!()[], and all other signs to be replaced with empty string. All occurences of - should not be replaced also.
I have used for this the XRegExp plugin but it seems I cannot find the magic solution :)
I have tryed like this :
var txt = "Ad СТИНГ (ALI) - Englishmen In New York";
var regex = new XRegExp('\\p{^N}\\p{^L}',"g");
var b = XRegExp.replace(txt, regex, "")
but the result is : AСТИН(AL EnglishmeINeYork ... which is kind of weird
If I try to add also the condition for not removing the '-' character leads to make the RegEx invalid.
\\p{^N}\\p{^L} means a non-number followed by a non-letter.
Try [^\\p{N}\\p{L}-] that means a non-number, non-letter, non-dash.
A jsfiddle where to do some tests... The third XRegExp is the one you asked.
\p{^N}\p{^L}
is a non-number followed by a non-letter. You probably meant to say a character that is neither a letter nor a number:
[^\p{N}\p{L}]
// all non letters/numbers in a string => /[^a-zA-z0-9]/g
I dont know XRegExp.
but in js Regexp you can replace it by
b.replace(/[^a-zA-z0-9]/g,'')