To check if a string is a valid latitude and longitude combination, we can use a regex expression in JavaScript.
TL;DR
// Regular expression to check if string is a latitude and longitude
const regexExp = /^((\-?|\+?)?\d+(\.\d+)?),\s*((\-?|\+?)?\d+(\.\d+)?)$/gi;
// String with latitude and longitude separated by comma
const str = "9.9824245,76.5703886";
regexExp.test(str); // true
This is the regex expression for matching almost all the test cases for a valid latitude and longitude combination in JavaScript.
// Regular expression to check if string is a latitude and longitude
const regexExp = /^((\-?|\+?)?\d+(\.\d+)?),\s*((\-?|\+?)?\d+(\.\d+)?)$/gi;
Now let's write a string with latitude and longitude like this,
// Regular expression to check if string is a latitude and longitude
const regexExp = /^((\-?|\+?)?\d+(\.\d+)?),\s*((\-?|\+?)?\d+(\.\d+)?)$/gi;
// String with latitude and longitude separated by comma
const str = "9.9824245,76.5703886";
Now to test the string, we can use the test() method available in the regular expression we defined. It can be done like this,
// Regular expression to check if string is a latitude and longitude
const regexExp = /^((\-?|\+?)?\d+(\.\d+)?),\s*((\-?|\+?)?\d+(\.\d+)?)$/gi;
// String with latitude and longitude separated by comma
const str = "9.9824245,76.5703886";
regexExp.test(str); // true
- The
test()method will accept astringtype as an argument to test for a match. - The method will return boolean
trueif there is a match using the regular expression andfalseif not.
See the above example live in JSBin.
If you want this as a utility function which you can reuse, here it is,
/* Check if string is a valid latitude and longitude */
function checkIfValidlatitudeAndlongitude(str) {
// Regular expression to check if string is a latitude and longitude
const regexExp = /^((\-?|\+?)?\d+(\.\d+)?),\s*((\-?|\+?)?\d+(\.\d+)?)$/gi;
return regexExp.test(str);
}
// Use the function
checkIfValidlatitudeAndlongitude("9.9824245,76.5703886"); // true
checkIfValidlatitudeAndlongitude("9.2323,1212notValid"); // false
That's all! 😃