2016-05-29 20 views
0

我正在採取正則表達式的第一步。我想增加一個url字符串中的最後一位數字,但由於某種原因,我不能找出我增加其他數字。使用JavaScript和正則表達式的URL操作

字符串:http://example.com/18-something-something/6

應該變成:http://example.com/19-something-something/7

正如你所看到的,18轉向19這是林試圖避免:http://example.com/18-something-something/7

在實踐

這是我的JS:

function isNumeric(n) { 
    return !isNaN(parseFloat(n)) && isFinite(n); 
} 

jQuery(document).ready(function() { 
    url = window.location.href; 

    var newrl = url.replace(/(\d+)+/g, function(match, number) { 
    return parseInt(number) + 1; 
    }); 

    var m = url.match(/\/([^\/]+)[\/]?$/); 
    link = jQuery('a[class=nextpostslink]').attr('href'); 

    if (!isNumeric(m[1])) { 
    jQuery('.post-content').find('img:first').wrap(jQuery("<div class='slideshow-wrapper'><a href=2>").attr("href", link)); 
    jQuery('.post-content').find('img:first').after('<div id="start-slideshow"><img src="chevron.png"></div>'); 
    } else { 
    jQuery('.post-content').find('img:first').wrap(jQuery("<div class='slideshow-wrapper'><a href=" + newrl + ">").attr("href", link)); 
    } 
}); 

任何想法,我缺少的是什麼? thx

+0

是總是關於在URL的末尾位數(注意後面的數字)?或者是關於網址中的最後一位數字,並且可以跟隨數字? –

+0

可能有查詢字符串參數。但路徑本身(沒有參數的url)將總是以我想增加的數字結尾 –

回答

-1

我不會這樣做與正則表達式,如實。

我會做這樣的事情:

var url = "http://example.com/18-something-something/6"; 
 

 
function advanceUrl(url) { 
 
    // Split the URL into chunks 
 
    var chunks = url.split("/"); 
 

 
    // Get the last segment of the URL 
 
    var lastPage = chunks.pop(); 
 

 
    // Increment it 
 
    lastPage++; 
 

 
    // And put it back 
 
    chunks.push(lastPage); 
 

 
    // Re-create the URL 
 
    var newUrl = chunks.join("/"); 
 

 
    // Log it 
 
    console.log(newUrl); 
 

 
    // Return it. 
 
    return newUrl; 
 
} 
 

 
advanceUrl(url);

+0

在你的回答結果中是'http://theviraldance.com/18-celebrities-who-look-amazingly-alike/6/ 1' –

0

你應該使用/(\d+)$/作爲一個正則表達式來僅增加了最後一位。

1

你不希望有一個全局匹配(g),但單獨刪除該標誌將無濟於事。

如果你想匹配與不查詢參數,那麼你需要確保它無論是在字符串的結尾$或前右側的查詢參數?讓你的正則表達式有看起來像這樣:

var url = 'http://example.com/18-something-something/6?param=34'; 
 

 
var newrl = url.replace(/(\d+)($|\?)/, function(match, number, questionmark) { 
 
    return String(++number) + questionmark; 
 
}); 
 

 
console.log(newrl);