JavaScript 正则表达式替换以 function 开头 { 结尾的内容
可以使用以下正则表达式进行替换:
str.replace(/function[\s\S]*?\{[\s\S]*?}/g, '')
其中,/function[\s\S]*?\{[\s\S]*?}/g 匹配以 'function' 开头,'{' 结尾的内容,[\s\S]*? 匹配任意字符(包括换行符),g 表示全局匹配。
示例代码:
const str = `
function test1() {
console.log('test1');
}
function test2() {
console.log('test2');
}
console.log('hello world');
`;
const result = str.replace(/function[\s\S]*?\{[\s\S]*?}/g, '');
console.log(result);
// 输出:
//
// console.log('hello world');
上述代码中,result 的值为 console.log('hello world');,即替换掉了以 'function' 开头,'{' 结尾的内容。
原文地址: https://www.cveoy.top/t/topic/leDM 著作权归作者所有。请勿转载和采集!