VERYはdummiedダウンアプローチ:
$('#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
を贅沢チェックサムはありません、エラーチェックなどwindow.location
または含む文字列を使用し、ここFromt必要に応じてURL。
機能(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