我有一个字符串 http://localhost:4502/mnt/override/apps/cms/components/content/carousel/_cq_dialog.html/content/cms/en/home/kids
我想通过删除以 mnt 开头并以 _cq_dialog.html 结尾的部分来修改此字符串,以便我的输出为
http://localhost:4502/content/cms/en/home/kids
答案 0 :(得分:0)
它不是 regex
而是使用 indexOf
(搜索所需字符串的位置)。
代码中有例子/说明/:
//your url
var url='http://localhost:4502/mnt/override/apps/cms/components/content/carousel/_cq_dialog.html/content/cms/en/home/kids';
//get position of /mnt - start position for "deleting"
var st=url.indexOf('/mnt');
//get position of 2nd condition and added 15 (length of 2nd condition)
var en=url.indexOf('_cq_dialog.html/'); en+=15;
//get all strings from very beginnig until start position of 1st condition
var newUrl=url.substr(0,st);
//get strings from end of 2nd condition to end of complete url string
newUrl+=url.substr(en,url.length-en);
//show result
var sp=document.getElementById('sp');
sp.innerHTML=newUrl;
<span id="sp"></span>
答案 1 :(得分:0)
您可能需要使用replace( /regex/,substitution ) 函数:
"http://localhost:4502/mnt/override/apps/cms/components/content/carousel/_cq_dialog.html/content/cms/en/home/kids".replace( /mnt.*(?=content\/cms)/, "" )
输出:
http://localhost:4502/content/cms/en/home/kids
注意
look-ahead (?=<PATTERN>)
断言是现代 JS 中的新功能。
答案 2 :(得分:0)
使用正则表达式,您可以找到以第一个孤立的 /
开始并以第一次出现的 .html/
结束的子字符串,并将其替换为 /
:
let s = "http://localhost:4502/mnt/override/apps/cms/components/content/carousel/_cq_dialog.html/content/cms/en/home/kids";
let res = s.replace(/\b\/\b.*?\.html\//, "/");
console.log(res);
答案 3 :(得分:0)
如果您想要一个正则表达式,我会使用@evolutionxbox 的解决方案,即使用 /mnt.+?_cq_dialog\.html\//
的正则表达式和 Javascript 的 string.replace
函数将字符串替换为 ''
。
但是,如果 URL 的内部部分不会改变,那么您就不需要正则表达式。你可以简单地做input.replace('mnt/override/apps/cms/components/content/carousel/_cq_dialog.html/', '');
然后,如果 URL 的内部部分存在,它将被删除。