简体   繁体   English

用Javascript中的正则表达式替换

[英]Replace with regular expression in Javascript

I have this regular expression: 我有这个正则表达式:

var a = window.location.href.replace(/((.*)[&|?])(sessionid(=[^&]*))([&|#](.*))/, '$1$5');

That remove the sessionid from an example url like this: 这样可以从示例网址中删除sessionid,如下所示:

http://...&parent_location=Test&abc=123&sessionid=q26bh6bkm8g49aeopem2obdm87igrsfe&...

The result will be: 结果将是:

http://...&parent_location=Test&abc=123&&...

My question is, if in that replace I can add the replace also for the parent_location 我的问题是,如果在该替换中,我还可以为parent_location添加替换

Use single regex with unnecessary capturing group removed. 使用单个正则表达式,删除不必要的捕获组。

str.replace(/([&?])(?:sessionid|parent_location)=[^&#]*(?=[&#]|$)/m, '$1')

DEMO 演示

You can add several .replace methods in a row. 您可以连续添加几个.replace方法。

var a = window.location.href
    .replace(/((.*)[&|?])(sessionid(=[^&]*))([&|#](.*))/, '$1$5')
    .replace(/*statement*/);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM