Hello Universe
Hello Universe

Reputation: 3302

How to get last element of url stripping out unwanted characters?

I am trying to capture the last element of the url and strip out any unwanted characters such as below

http://www.myurl.com/abcs/der/er/..../asdsad/hrllo.shtml#header?query=whatever&....

from the above URl, for example, I need to get only hrllo

var search_param = $(location).attr("href").split('/').pop().replace('#', '');

I think maybe a regex? the text hrllo can only have letters (capital or not).

Upvotes: 1

Views: 135

Answers (2)

Lewis
Lewis

Reputation: 14866

If your query string contains dots or slashes, it should be removed first.

str.slice(0,str.indexOf('?'));

Otherwise, this one will be good enough.

str.slice(str.lastIndexOf('/')+1,str.lastIndexOf('.'));

Upvotes: 2

Mottie
Mottie

Reputation: 86413

Try splitting it at the hash instead, like this (demo):

var url = [
    "http://www.myurl.com/abcs/der/er/.../asdsad/hrllo1.shtml#header?query=whatever&....",
    "http://www.myurl.com/abcs/der/er/.../asdsad/hrllo2.shtml?query=whatever",
    "http://www.myurl.com/abcs/der/er/..../asdsad/hrllo3.shtml",
    "http://myurl.com/index3.html#query=twitter.com/search"
  ],
  i, left, index, page = [];
for (i = 0; i < url.length; i++) {
  left = url[i].split(/[#?]/g)[0];
  index = left.lastIndexOf('/') + 1;
  page.push(left.slice(index));
}

// result: page = [ 'hrllo1.shtml', 'hrllo2.shtml', 'hrllo3.shtml' ];

Upvotes: 1

Related Questions