Skip to content

Commit fc5af6d

Browse files
committed
Fix #199 – Allow regexes in array
1 parent 8d77abc commit fc5af6d

File tree

3 files changed

+38
-6
lines changed

3 files changed

+38
-6
lines changed

package.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
{
22
"name": "replace-in-file",
33
"type": "module",
4-
"version": "8.1.0",
4+
"version": "8.2.0",
55
"description": "A simple utility to quickly replace text in one or more files.",
66
"homepage": "https://github.com/adamreisnz/replace-in-file#readme",
77
"author": {

src/helpers/config.js

Lines changed: 25 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,30 @@ export async function loadConfig(file) {
1717
return JSON.parse(json)
1818
}
1919

20+
/**
21+
* Helper to convert a string to Regex if it matches the pattern
22+
*/
23+
export function stringToRegex(str) {
24+
25+
//Array given
26+
if (Array.isArray(str)) {
27+
return str.map(stringToRegex)
28+
}
29+
30+
//Not a string, or no match
31+
const regexMatch = /.*\/([gimyus]*)$/
32+
if (typeof str !== 'string' || !str.match(regexMatch)) {
33+
return str
34+
}
35+
36+
//Extract flags and pattern
37+
const flags = str.replace(/.*\/([gimyus]*)$/, '$1')
38+
const pattern = str.replace(new RegExp(`^/(.*?)/${flags}$`), '$1')
39+
40+
//Return regex
41+
return new RegExp(pattern, flags)
42+
}
43+
2044
/**
2145
* Parse config
2246
*/
@@ -66,11 +90,7 @@ export function parseConfig(config) {
6690
}
6791

6892
//Since we can't store Regexp in JSON, convert from string if needed
69-
if (typeof from === 'string' && from.match(/.*\/([gimyus]*)$/)) {
70-
const flags = from.replace(/.*\/([gimyus]*)$/, '$1')
71-
const pattern = from.replace(new RegExp(`^/(.*?)/${flags}$`), '$1')
72-
config.from = new RegExp(pattern, flags)
73-
}
93+
config.from = stringToRegex(from)
7494

7595
//Use default encoding if invalid
7696
if (typeof encoding !== 'string' || encoding === '') {

src/helpers/config.spec.js

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -185,6 +185,18 @@ describe('helpers/config.js', () => {
185185
expect(parsed.from).to.be.an.instanceof(RegExp)
186186
})
187187

188+
it('should convert from an array of regexes if provided in JSON', async () => {
189+
const parsed = parseConfig({
190+
files: ['file.txt'],
191+
from: ['/foo/g', '/baz/g', 'plain'],
192+
to: 'bar',
193+
})
194+
expect(parsed.from).to.be.an.instanceof(Array)
195+
expect(parsed.from[0]).to.be.an.instanceof(RegExp)
196+
expect(parsed.from[1]).to.be.an.instanceof(RegExp)
197+
expect(parsed.from[2]).to.equal('plain')
198+
})
199+
188200
it('should not convert from regex if it is a regular string', async () => {
189201
const parsed = parseConfig({
190202
files: ['file.txt'],

0 commit comments

Comments
 (0)