0

I have a url, like this:

http://google.com/foo/querty?act=potato
http://google.com/foo/querty/?act=potato
http://google.com/foo/querty/#/21312ads
http://google.com/foo/querty#/1230982130asd

How can i get only the "querty" string by using regex in javascript for this format of URL?

3 Answers 3

1

To match URLs with "?":

str.match(/^.*\/([^\/]+)\/?\?.*$/)[1];

To match URLs with "#":

str.match(/^.*\/([^\/]+)\/?#.*$/)[1];

to match both:

str.match(/^.*\/([^\/]+)\/?[#\?].*$/)[1];
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for that answer, i've edited my question with a new information. Unfortunately, if i use a www.foo.bar/123#/abc the regular expression takes the abc. How add the (#) to the regex?
Sorry, i forgot to enter the new question. I need the regex check the # too... like: www.google.com.br/foo/#/bar i want the regex to take only the foo cause bar isn't a "true directory".
1

I'd suggest:

var url = "http://google.com/foo/querty?act=potato".split('/').pop(),
    urlPart = url.slice(0,url.indexOf('?'));
    console.log(urlPart);

I'd strongly suggest not using regular expressions for this, given the needless complexity (but that is, of course, a personal preference).

Edited to address the failure of the above to meet both test-cases shown in the question (it fails in the second case). The following handles both cases specified:

Object.prototype.lastStringBefore = function (char, delim) {
    if (!char) {
        return this;
    }
    else {
        delim = delim || '/';
        var str = this,
            index = str.indexOf(char),
            part = str.charAt(index - 1) == delim ? str.split(delim).slice(-2, -1) : str.split(delim).pop();
        return part.length === 1 ? part[0] : part.slice(0, part.indexOf(char));
    }
}

var url1 = 'http://google.com/foo/querty?act=potato',
    url2 = 'http://google.com/foo/querty/?act=potato',
    lastWord1 = url1.lastStringBefore('?', '/'),
    lastWord2 = url2.lastStringBefore('?', '/');

console.log(lastWord1, lastWord2);

JS Fiddle demo.

References:

1 Comment

You're right, of course; edited to correct that short-coming. Thanks for the catch!
0

Use lastIndexOf to find the ? and substr to extract part of your string:

url.substr(url.lastIndexOf('?'));

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.