我想从我拥有的网址中删除/view-photo/P1270649
。我目前正在使用它来执行此操作:
var pathname = window.location.pathname;
var replaced = pathname.replace('/view-photo/' + /([A-Z0-9]+)/g, '');
然而,当我尝试使用它时没有任何反应。你可以see it in action on JSFiddle。我该如何解决这个问题?
答案 0 :(得分:9)
您不能以这种方式组合字符串和正则表达式。最简单的方法是将它完全放在正则表达式中:
var replaced = pathname.replace(/\/view-photo\/([A-Z0-9]+)/g, '');
最初发生的事情是正则表达式对象被转换为字符串,这实际上使您的replace()
看起来像这样:
var replaced = pathname.replace("/view-photo//([A-Z0-9]+)/g", '');
...会搜索该字符串的文字版本,当然不存在。
答案 1 :(得分:1)
构建正则表达式时,'字符失败:
var replaced = pathname.replace('/view-photo/' + /([A-Z0-9]+)/g, '');
应该是
var replaced = pathname.replace(/view-photo/([A-Z0-9]+)/g, '');
答案 2 :(得分:1)
我会建议另一种方法(纯粹的js)
var pathname = window.location.pathname;
var i = pathname.slice(0,pathname.indexOf('/view-photo'));
答案 3 :(得分:0)
试试这个,
$(document).ready(function() {
var pathname = 'http://localhost/galleri/view-photo/P1270649';
var replaced = pathname.replace(/view-photo\/([A-Z0-9]+)/g, '');
// or you can use it like
//var replaced = pathname.replace(/\/view\-photo\/([A-Z0-9]+)/g, '');
alert(replaced);
});