Refine replacement of Regex

pull/10616/head
Andrew Watkins 2018-06-27 12:09:40 -07:00
parent f47981f362
commit 5f0a0ae24d
2 changed files with 23 additions and 5 deletions

View File

@ -82,14 +82,21 @@ const replaceAllRegex = (
search: string,
replacement: string
) => {
// check for presence of anythine between two forward slashes /[your stuff here]/
const matches = query.match(/\/([^\/]*)\//gm)
const isReplaceable = !!matches && matches.some(m => m.includes(search))
if (!isReplaceable) {
if (!matches) {
return query
}
return replaceAll(query, search, replacement)
return matches.reduce((acc, m) => {
if (m.includes(search)) {
const replaced = m.replace(search, replacement)
return acc.split(m).join(replaced)
}
return acc
}, query)
}
const replaceAll = (query: string, search: string, replacement: string) => {

View File

@ -88,6 +88,17 @@ describe('templates.utils.replace', () => {
},
],
},
{
...emptyTemplate,
tempVar: ':region:',
values: [
{
type: TemplateValueType.TagValue,
value: 'north',
selected: true,
},
],
},
{
...emptyTemplate,
tempVar: ':dashboardTime:',
@ -101,8 +112,8 @@ describe('templates.utils.replace', () => {
},
]
const query = `SELECT "usage_active" FROM "cpu" WHERE host =~ /^:host:$/ AND time > :dashboardTime: FILL(null)`
const expected = `SELECT "usage_active" FROM "cpu" WHERE host =~ /^my-host.local$/ AND time > now() - 1h FILL(null)`
const query = `SELECT "usage_active" FROM "cpu" WHERE host =~ /^:host:$/ AND host = :host: AND region =~ /:region:/ AND time > :dashboardTime: FILL(null)`
const expected = `SELECT "usage_active" FROM "cpu" WHERE host =~ /^my-host.local$/ AND host = 'my-host.local' AND region =~ /north/ AND time > now() - 1h FILL(null)`
const actual = templateReplace(query, vars)
expect(actual).toBe(expected)