JavaScript / ECMAScript

MongoDB Connection URI in JS

Match MongoDB connection URIs in both standard `mongodb://` and SRV `mongodb+srv://` formats.

Try it in the JS tester →

Pattern

regexJS
mongodb(?:\+srv)?:\/\/(?:[^:@\s]+(?::[^@\s]*)?@)?[^\/?\s]+(?:\/[^?\s]*)?(?:\?\S*)?   (flags: g)

JavaScript / ECMAScript code

jsJavaScript
const re = new RegExp("mongodb(?:\\+srv)?:\\/\\/(?:[^:@\\s]+(?::[^@\\s]*)?@)?[^\\/?\\s]+(?:\\/[^?\\s]*)?(?:\\?\\S*)?", "g");
const input = "Conn: mongodb://user:pass@cluster0.mongodb.net:27017/mydb";
const matches = [...input.matchAll(re)];
console.log(matches.map(m => m[0]));

Uses `String.prototype.matchAll` for global iteration (Node 12+ / all modern browsers).

How the pattern works

mongodb(?:\+srv)?:\/\/ matches either scheme. (?:[^:@\s]+(?::[^@\s]*)?@)? optionally matches user[:password]@. [^\/?\s]+ matches the host (potentially comma-separated for replica sets, though this regex captures only up to the first / or ?). (?:\/[^?\s]*)? optionally matches the database path. (?:\?\S*)? optionally matches query parameters.

Examples

Input

Conn: mongodb://user:pass@cluster0.mongodb.net:27017/mydb

Matches

  • mongodb://user:pass@cluster0.mongodb.net:27017/mydb

Input

mongodb+srv://admin@prod.example.com/main?retryWrites=true

Matches

  • mongodb+srv://admin@prod.example.com/main?retryWrites=true

Input

no connection here

No match

Same pattern, other engines

← Back to MongoDB Connection URI overview (all engines)