js正则 replace 反向引用的问题。

2018-11-06 09:43:15 浏览数 (1)

目前在配置node express 的 url rewrite

Before the URL gets to Express' static middleware, we need to rewrite the URL. 参考

代码语言:javascript复制
var app = express();
// Rewrite the URL before it gets to Express' static middleware. 
app.use('/public/', function(req, res, next) {
        req.url = req.url.replace(//([^/] ).[0-9a-f] .(css|js|jpg|png|gif|svg)$/, "/$1.$2");
        next();
});
app.use('/public/', express['static'](__dirname   '/public', { maxAge: 30 }));
代码语言:javascript复制
//现在想把 :

var url = 'http://localhost:8080/newcss/act/act1/index.html/aaa';          //替换为:
          'http://localhost:8080/newcss/act/act1/index.html';
          
> url.replace(/(/newcss/. ?index.html)/,"$1");
> "http://localhost:8080/newcss/act/act1/index.html/aaa"          //不生效

//我们来看下match的

url.match(/(/newcss/. ?index.html)/)
>[ "/newcss/act/act1/index.html",
   "/newcss/act/act1/index.html",          //$1
   index: 21,
   input: "http://localhost:8080/newcss/act/act1/index.html/aaa"
 ]


//match的结果完全正常,而且 $1 就是我们想要的,但是为什么就replace不行了呢?????



//我在replace后再加一个括号匹配剩下的url就正常了。如下:

> url.replace(/(/newcss/. ?index.html)(.*)?/,"$1")
> "http://localhost:8080/newcss/act/act1/index.html"



0 人点赞