非常空置向下的方法:
$('#parse').click(function(e){
var fromUrl = $('#from-url').val();
var newNum = parseInt($('#new-number').val(), 10);
var urlRE = /(?!\?)(\d+)$/;
if (urlRE.test(fromUrl)){
$('#result').text(fromUrl.replace(urlRE, newNum));
}else{
$('#result').text('Invalid URL');
}
});
DEMO
有沒有奢侈的檢驗和,錯誤檢查等Fromt這裏,使用window.location
或包含字符串網址,如果需要。
的爆發給一個函數(demo):「?」
// Call this to replace the last digits with a new number within a url.
function replaceNumber(url, newNumber){
// regex to find (and replace) the numbers at the end.
var urlRE = /\?\d+$/;
// make sure the url end in a question mark (?) and
// any number of digits
if (urlRE.test(url)){
// replace the ?<number> with ?<newNumber>
return url.replace(urlRE, '?'+newNumber);
}
// invalid URL (per regex) just return same result
return url;
}
alert(replaceNumber('http://website.com/avatars/avatar.png?56', 57));
有沒有使用正則表達式具體原因是什麼?你可以使用'location'對象,分別使用'location.search'。 –
你的正則表達式是一個好的。你只需要重新加入你拿出的'?'中。請參閱下面的答案。 – ridgerunner