0

I need to be able to grab the number at the end of the url, and set it as the value of a textbox. I have the following, but it's not correctly stripping out the beginning of the URL before the last slash. Instead, its doing the opposite.

<input id="imageid"></input>

var referrerURL = "http://subdomain.xx-xxxx-x.xxx.url.com/content/assets/750";
var assetID = referrerURL.match("^(.*[\\\/])");
$("#imageid").val(assetID);

The result of the regex match should set the value of the text box to 750 in this case.

JSFiddle: Link

4 Answers 4

7

The simple method is to use a negated character class as

/[^\/]*$/

Regex Demo

Example

var referrerURL = "http://subdomain.xx-xxxx-x.xxx.url.com/content/assets/750";
alert(referrerURL.match(/[^\/]*$/));
// Output
// => 750
Sign up to request clarification or add additional context in comments.

1 Comment

Will do, just waiting for the timer to end (can't accept an answer so quickly after its been posted apparently)
1

Can use a simple split() and then pop() the resultant array

var assetID = referrerURL.split('/').pop();

Easier to read than a regex thus very clear what it is doing

DEMO

Comments

1

var referrerURL = "http://subdomain.xx-xxxx-x.xxx.url.com/content/assets/750";
var myregexp = /.*\/(.*?)$/;
var match = myregexp.exec(referrerURL);
$("#imageid").val(match[1]);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input id="imageid"></input>

Comments

0

You could try avoiding the usage of regular expression for this task just by using native javascript's string functions.

  • Splitting the text:

    var lastSlashToken = referrerURL.split("/").pop(-1);
    
  • Looking up for the last ending "/text" token:

    var lastSlashToken = referrerURL.substr(referrerURL.lastIndexOf("/") + 1);
    

However, if you still want to use regular expression for this task, you could try using the following pattern:

.*\/([^$]+)

Regular expression visualization

Working DEMO example @ regex101

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.