简体   繁体   中英

Remove last element from url

I need to remove the last part of the url from a span..

I have

<span st_url="http://localhost:8888/careers/php-web-developer-2"
st_title="PHP Web Developer 2" class="st_facebook_large" displaytext="facebook"
st_processed="yes"></span></span>

And I need to take the st_url and remove the php-web-developer-2 from it so it is just http://localhost:8888/careers/ .

But I am not sure how to do that. php-web-developer-2 will not always be that but it won't have any / in it. It will always be a - separated string.

Any Help!!??

as simple as this:

var to = url.lastIndexOf('/');
to = to == -1 ? url.length : to + 1;
url = url.substring(0, to);
$('span').attr('st_url', function(i, url) {
    var str = url.substr(url.lastIndexOf('/') + 1) + '$';
    return url.replace( new RegExp(str), '' );
});

DEMO

Use this.

$('span').attr('st_url', function(i, url) {
    var to = url.lastIndexOf('/') +1;

    x =  url.substring(0,to);
    alert(x);
})​

You can see Demo

You could use a regular expression to parse the 'last piece of the url':

var url="http://localhost:8888/careers/php-web-developer";

var baseurl=url.replace(
    new RegExp("(.*/)[^/]+$"),
    "$1") );

The RegExp thing basically says: "match anything, then a slash and then all non-slashes till the end of the string".

The replace function takes that matching part, and replaces it with the "anything, then a slash" part of the string.

RegexBuddy has a great deal of information on all this.

You can see it work here: http://jsfiddle.net/xKxLR/

var url = "http://localhost:8888/careers/php-web-developer-2";
var regex = new RegExp('/[^/]*$');
console.log(url.replace(regex, '/'));

First you need to parse the tag. Next try to extract st_url value which is your url. Then use a loop from the last character of the extracted url and omit them until you see a '/'. This is how you should extract what you want. Keep this in mind and try to write the code .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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