Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/18.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
加入";。js";在JavaScript中使用replace with regex进行扩展_Javascript_Regex_String_Replace - Fatal编程技术网

加入";。js";在JavaScript中使用replace with regex进行扩展

加入";。js";在JavaScript中使用replace with regex进行扩展,javascript,regex,string,replace,Javascript,Regex,String,Replace,假设我必须导入语句 // 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'; 在整个代码字符串中 在JavaScrip

假设我必须导入语句

// 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中用正则表达式替换的正确方法是什么

全局
情况下
匹配

str.replace(regexp,newSubstr |函数)


谢谢。

查找以
import
开头并包含斜杠的行,后跟非斜杠、非句点字符,并对
['”];?
进行前瞻,以标识字符串的结尾和行:

const codeStr=`
//其他代码。。。
从“./some/bar”导入*作为Foo;
从“./dir/qux”导入{baz};
从'./dir/bar.js'导入{bar};
//其他代码。。。
`;
console.log(
codeStr.replace(/import.+\/[^\/\.]+(?=['”];?$)/gm,'$&.js')
);请尝试以下操作:

let match = /(import.*)("|');/g.exec(`import { baz } from './dir/qux';`)
然后您会得到以下列表:

(3) ["import { baz } from './dir/qux';", "import { baz } from './dir/qux", "'", index: 0, input: "import { baz } from './dir/qux';", groups: undefined]
您只需要在元素1和元素2之间添加.js

match[1]+".js"+match[2]
这似乎有效

查找:
/^(从[^\S\r\n]*([“'))(((?:(?!(?:\.js)?\2)[\S\S])+(\2\S*)/mg导入[^\S\r\n].+?[^\S\r\n]

替换:
$1$3.js$4

可读正则表达式

 ^                             # BOL
 (                             # (1 start), Preamble
      import [^\S\r\n] .+? 
      [^\S\r\n] 
      from [^\S\r\n]* 
      ( ["'] )                      # (2), Delimiter
 )                             # (1 end)
 (                             # (3 start), Body
      (?:
           (?!
                (?: \.js )?
                \2 
           )
           [\S\s] 
      )+
 )                             # (3 end)
 ( \2 \s* ; )                  # (4), Postfix

如果文件夹中只有一个同名文件或类似文件,文件扩展名不是已经是可选的了吗?您是否尝试过自己编写任何这样的正则表达式?看起来很简单,您只需要查找以
import
开头的行,然后在end@CertainPerformance ,我没有使用Bundler,这就是为什么要问这个问题。如果它足够简单,为什么你不给我一个答案,我调查并决定接受它。谢谢。谢谢,我喜欢你的解决方案。你还聪明地添加了一个额外的功能,以避免重复的*js。非常感谢,