假设我必须导入语句
// other code...
import * as Foo from "../some/bar";
import { baz } from './dir/qux';
// other code...
我想在上述每个文件的末尾添加一个 .js
扩展名,用单/双引号括起来,如下所示
import * as Foo from "../some/bar.js";
import { baz } from './dir/qux.js';
在整个代码字符串中。
在 JavaScript 中用正则表达式替换的正确方法是什么?
在global
和case
中匹配
str.replace(regexp, newSubstr|function)
谢谢。
最佳答案
查找以 import
开头且包含斜杠、后跟非斜杠、非句点字符的行,并通过前向查找 ['"];?
来识别字符串和行的结尾:
const codeStr = `
// other code...
import * as Foo from "../some/bar";
import { baz } from './dir/qux';
import { bar } from './dir/bar.js';
// other code...
`;
console.log(
codeStr.replace(/import .+\/[^\/\.]+(?=['"];?$)/gm, '$&.js')
);
关于javascript - 在 JavaScript 中使用正则表达式替换添加 ".js"扩展,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51851456/