从 mysql 连接字符串中获取数据库名称?

get database name from mysql connection string?

有没有办法从 MySql 连接字符串中获取数据库名称?

例如MySQL数据字符串可以是这两种类型中的任何一种。

我)。 mysql://root:password@localhost/test

ii). mysql://root:password@localhost/test?debug=true&charset=BIG5_CHINESE_CI&timezone=-0700

那么如何获取像'test'这样的数据库名称(在本例中)。来自以上两个给定字符串中的任何一个?

谢谢:)

如果正则表达式是一个选项,这是一种方法:

var regex = /\/([^\/\?]+)(?:\?.+)?$/;

"mysql://root:password@localhost/test".match(regex)[1]

"mysql://root:password@localhost/test?debug=true&charset=BIG5_CHINESE_CI&timezone=-0700".match(regex)[1]

Node.js 的 built-in URL 模块将能够可靠地解析您的示例连接字符串。

var url = require('url')
var parsed = url.parse('mysql://root:password@localhost/test?debug=true&charset=BIG5_CHINESE_CI&timezone=-0700')
var databaseName = parsed.pathname