admin管理员组

文章数量:1395785

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 = "";
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

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./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

Share Improve this question asked May 4, 2015 at 15:56 MattMatt 1,2675 gold badges26 silver badges54 bronze badges
Add a ment  | 

4 Answers 4

Reset to default 7

The simple method is to use a negated character class as

/[^\/]*$/

Regex Demo

Example

var referrerURL = "http://subdomain.xx-xxxx-x.xxx.url./content/assets/750";
alert(referrerURL.match(/[^\/]*$/));
// Output
// => 750

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

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

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:

.*\/([^$]+)

Working DEMO example @ regex101

本文标签: jqueryGrab the end of a URL after the last slash with regex in javascriptStack Overflow