wyc
wyc

Reputation: 55263

Matching the last word in an URL with JavaScript

The URL looks like this:

http://www.example.com/?lessoncontent=lesson-003-pinyin

I managed to get the last part with this:

var url = window.location.href.split("/").pop();

So now I got this:

?lessoncontent=lesson-003-pinyin

Not sure how to get the last part, though (pinyin). I want to be able to do if statements with URLs like this:

?lessoncontent=lesson-001-pinyin
?lessoncontent=lesson-003-pinyin
?lessoncontent=lesson-002-complete
?lessoncontent=lesson-003-complete

(Only taking into account the last word of the URL).

Example:

if (match === "pinyin") { //do stuff }
if (match === "complete") { //do stuff }

Upvotes: 0

Views: 717

Answers (4)

user2575725
user2575725

Reputation:

You may try RegExp:

var match = location.search.match(/(\w+)$/)[0]
if (match === "pinyin") { //do stuff }
if (match === "complete") { //do stuff }

Here, location.search will only the parameters i.e. ?lessoncontent=lesson-001-pinyin. Next match(/(\w+)$/) gives you an array of matching words from the end of string.

Upvotes: 1

vks
vks

Reputation: 67968

[^-]*$

Try this.See demo.You can direclty apply this over the link and get the answer in one step.

https://regex101.com/r/wU7sQ0/16

var re = /[^-]*$/gm;
var str = 'http://www.example.com/?lessoncontent=lesson-003-pinyin';
var m;

while ((m = re.exec(str)) != null) {
if (m.index === re.lastIndex) {
re.lastIndex++;
}
// View your result using the m-variable.
// eg m[0] etc.
}

Upvotes: 1

David Faber
David Faber

Reputation: 12486

I would try this:

(\w+)[&?\/]?$

which will work for all sorts of URLs, for example whether there is a URL parameter or not. It will get all the word characters up to a optional trailing &, ?, or /. See Regex 101 Demo here.

Upvotes: 1

Amit Joki
Amit Joki

Reputation: 59232

Just split on - and take the last element from it.

var match = window.location.href.split("-").pop();
if (match === "pinyin") {}  // do stuff 
if (match === "complete") {} // do stuff

We are splitting on - and then, taking the last element in it by popping it out of the Array.

Upvotes: 3

Related Questions