Regex checking lat/lon in JavaScript - javascript

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

Related

Converting ## to number regex

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="#">

How to convert string from PHP to javascript regular expression?

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)

Matching a string with a regex gives null even though it should match

I am trying to get my regex to work in JavaScript, but I have a problem.
Code:
var reg = new RegExp('978\d{10}');
var isbn = '9788740013498';
var res = isbn.match(reg);
console.log(res);
However, res is always null in the console.
This is quite interesting, as the regex should work.
My question: then, what is the right syntax to match a string and a regex?
(If it matters and could have any say in the environment: this code is taken from an app.get view made in Express.js in my Node.js application)
Because you're using a string to build your regex, you need to escape the \. It's currently working to escape the d, which doesn't need escaping.
You can see what happens if you create your regex on the chrome console:
new RegExp('978\d{10}');
// => /978d{10}/
Note that there is no \d, only a d, so your regex matches 978dddddddddd. That is, the literal 'd' character repeated 10 times.
You need to use \\ to insert a literal \ in the string you're building the regex from:
var reg = new RegExp('978\\d{10}');
var isbn = '9788740013498';
var res = isbn.match(reg);
console.log(res)
// => ["9788740013498", index: 0, input: "9788740013498"]
You need to escape with double back slash if you use RegExp constructor:
var reg = new RegExp('978\\d{10}');
Quote from documentation:
When using the constructor function, the normal string escape rules (preceding special characters with \ when included in a string) are necessary. For example, the following are equivalent:
var re = /\w+/;
var re = new RegExp("\\w+");

Convert string to regex using regexp and test values in javascript

I have a regular expression that is in string form, I want to bind that regex to my grid cell. Such that, now the values in that cell are validated against that regex. I am using RegExp JavaScript library for conversion and testing the value. But it is either returning false everytime or giving me an invalid regex, even for the simplest of the regex used.
This is the method I am using:
addCellValidator(columnObj[0].name, new CellValidator({
isValid: function (value) {
var regex = new RegExp("/^[a-zA-Z\-]+$/");
return value == "" || (regex.test(value));
}
}));
Is it the format or any special pattern required by the RegExp?
While this is valid JavaScript code:
new RegExp("/^[a-zA-Z\-]+$/")
... it doesn't generate the regular expression you think. It's equivalent to this:
/\/^[a-zA-Z-]+$\//
You'll have to:
Strip delimiters
Extract and parse flags, if any, e.g.:
"/^[a-z-]+$/i" ---> new RegExp("^[a-z-]+$", "i")
One more note: there's no point in escaping - with backslash. If want to match a literal - inside a character class you need to put it as first or last item.
You just added the / / to the string, this works:
addCellValidator(columnObj[0].name, new CellValidator({
isValid: function (value) {
var regex = new RegExp("^[a-zA-Z\-]+$");
return value == "" || (regex.test(value)); }
}));

assign matched values from jquery regex match to string variable

I am doing it wrong. I know.
I want to assign the matched text that is the result of a regex to a string var.
basically the regex is supposed to pull out anything in between two colons
so blah:xx:blahdeeblah
would result in xx
var matchedString= $(current).match('[^.:]+):(.*?):([^.:]+');
alert(matchedString);
I am looking to get this to put the xx in my matchedString variable.
I checked the jquery docs and they say that match should return an array. (string char array?)
When I run this nothing happens, No errors in the console but I tested the regex and it works outside of js. I am starting to think I am just doing the regex wrong or I am completely not getting how the match function works altogether
I checked the jquery docs and they say that match should return an array.
No such method exists for jQuery. match is a standard javascript method of a string. So using your example, this might be
var str = "blah:xx:blahdeeblah";
var matchedString = str.match(/([^.:]+):(.*?):([^.:]+)/);
alert(matchedString[2]);
// -> "xx"
However, you really don't need a regular expression for this. You can use another string method, split() to divide the string into an array of strings using a separator:
var str = "blah:xx:blahdeeblah";
var matchedString = str.split(":"); // split on the : character
alert(matchedString[1]);
// -> "xx"
String.match
String.split

Categories

Resources