Reputation: 6436
I want to remove /view-photo/P1270649
from an URL that I have. I'm currently using this to do so:
var pathname = window.location.pathname;
var replaced = pathname.replace('/view-photo/' + /([A-Z0-9]+)/g, '');
However, nothing happens when I try to use this. You can see it in action on JSFiddle. How can I fix this issue?
Upvotes: 0
Views: 180
Reputation: 16020
You can't combine a string and a regular expression in that way. The simplest thing to do would be to place it entirely in the regex:
var replaced = pathname.replace(/\/view-photo\/([A-Z0-9]+)/g, '');
What happened originally was that the regular expression object was being converted into a string, which would actually made your replace()
look something like this:
var replaced = pathname.replace("/view-photo//([A-Z0-9]+)/g", '');
...which would have searched for the literal version of that string, which of course is not there.
Upvotes: 9
Reputation: 2557
i would suggest another approach (pure js)
var pathname = window.location.pathname;
var i = pathname.slice(0,pathname.indexOf('/view-photo'));
Upvotes: 1
Reputation: 40639
Try this,
$(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);
});
Upvotes: 0
Reputation: 3171
The ' character is failing when building the regex expression:
var replaced = pathname.replace('/view-photo/' + /([A-Z0-9]+)/g, '');
should be
var replaced = pathname.replace(/view-photo/([A-Z0-9]+)/g, '');
Upvotes: 1