开发者社区> 问答> 正文

javascript正规表达式替换问题

我要这样一段字符串需要用正则替换掉它:

var str="method:function(a,b,c){var c={a,b};function a(){}},handler:function(){}";

想要把function都替掉成为:

var str = "method:null,handler:null";

我这个问题匹配出错主要是{}主间的内容;

//内容  document.getE().a.b();类似组件可以出现任意次;
var re=/function\s*\((\w*(\,)?)*\)\s*\{([^\{\}])*\}/gi;
console.log(regStr.match(re).length);
console.log(regStr.match(re));
console.log(regStr.replace(re,"null"));
我目前只能匹配空函数类似于:

var str="method:function(){},action:function(){}";

对于函数的{}中如果有内容我就没法判断了用(.*)会匹配出错误的结果

哪位高手出来给我解释这问题

展开
收起
a123456678 2016-07-15 10:06:28 2069 0
1 条回答
写回答
取消 提交回答
  • var config = {title:'aa',onclick:function(){},items:[{button:{onclick:function(){}}}]},
            handler = function(config){
                for (var o in config){
                    if (!config.hasOwnProperty(o)) {
                        console.log('ignore %o => %o of %o', o, config[o], Object.prototype.toString.apply(config[o]));
                        continue;
                    }else if (config[o] && Object.prototype.toString.apply(config[o]) === '[object Function]') {
                        console.log('delete %o => %o of %o', o, config[o], Object.prototype.toString.apply(config[o]));
                        delete config[o];
                    }else if (Object.prototype.toString.apply(config[o]) === '[object Array]' || Object.prototype.toString.apply(config[o]) === '[object Object]') {
                        console.log('enter %o => %o of %o', o, config[o], Object.prototype.toString.apply(config[o]));
                        handler(config[o]);
                        console.log('return %o => %o of %o', o, config[o], Object.prototype.toString.apply(config[o]));
                    }else console.log('ignore %o => %o of %o', o, config[o], Object.prototype.toString.apply(config[o]));
                }
            };
    handler(config);
    /*
    结果
    ignore "title" => "aa" of "[object String]"
    delete "onclick" => function (){} of "[object Function]"
    enter "items" => [Object] of "[object Array]"
    enter "0" => Object of "[object Object]"
    enter "button" => Object of "[object Object]"
    delete "onclick" => function (){} of "[object Function]"
    return "button" => Object of "[object Object]"
    return "0" => Object of "[object Object]"
    return "items" => [Object] of "[object Array]"
    */
    2019-07-17 19:56:44
    赞同 展开评论 打赏
问答排行榜
最热
最新

相关电子书

更多
JavaScript面向对象的程序设计 立即下载
Delivering Javascript to World 立即下载
编程语言如何演化-以JS的private为例 立即下载