I need to extract the hello/world
part of this URL:
http://example.com/#tags/hello/world
I'm totally confussed with split, replace and concat. W开发者_如何学JAVAhat's the best way to do it?
I'd do this:
var newString = oldString.replace('http://example.com/#tags/', '');
var result = "http://example.com/#tags/hello/world".replace("http://example.com/#tags/","");
For the fastest way use this
var result = "http://example.com/#tags/hello/world".slice(25);
try
function removePrefix(prefix,s) {
return s.substr(prefix.length);
}
removePrefix('http://example.com/#tags/','http://example.com/#tags/hello/world')
if this code is intended to working on the current page's URL you can use the window.location.hash
property to just get the anchor portion of the URL and take everything after the first forward-slash:
var h = window.location.hash;
var p = h.substring(h.indexOf('/') + 1);
[NB: this will fail if there is no forward-slash in the anchor]
If instead you need to do this for a URL which you've currently only got in a string variable you can get some help from your browser's own URL parser by creating a detached DOM element and reading its properties:
var a = document.createElement('a');
a.href = 'http://example.com/some/path/#tags/hello/world';
// a.hash now contains '#tags/hello/world'
var h = a.hash;
var p = h.substring(h.indexOf('/') + 1);
See http://jsfiddle.net/alnitak/xsEUW/ for a demo.
yourString = yourString.replace(/http:\/\/example\.com\/#tags\//, '');
Split creates an array out of a string using a character as a delimiter. so that is not really what you want, since you're trying to keep the end of the string, including what would be the natural delimiter.
substr removes the first n characters of a string. so you could do
var remove_string = 'http://example.com/#tags/'
path.substr(remove_string.length);
and it would work just fine.
Replace finds a given regular expression and replaces it with the second argument. so you could also do (note that the regular expression is contained within / /)
path = path.replace(/^http:\/\/example.com\/#tags\//,"")
A little uglier because of the escaping of characters but a bit more succinct.
Also as a previous poster did you could just pass the string to be matched to replace instead of the regex.
If we suppose http://example.com/#tags/ is the fixed part and the rest is variable
.
You could do the following
var content='http://example.com/#tags/hello/world';
var indicator='#tags';
var result=content.substring(content.indexOf(indicator)+indicator.length);
精彩评论