非常空置向下的方法:
$('#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