0

Im trying to use javascript and regex to replace a substring in a url.

myurl.com/?page_id=2&paged=2 

shall become

myurl.com/?page_id=2&paged=3

this is my code that doesnt seem to work:

nextLink = 'myurl.com/?page_id=2&paged=2'
nextLink = nextLink.replace(/\/paged\=\/[0-9]?/, 'paged='+ pageNum);

What am i doing wrong here? Im new to regex.

4

7 回答 7

2

你告诉它 match /paged,但/paged你的字符串中没有。此外,[0-9]?可能不是您想要的数字。尝试这个:

nextLink.replace(/\&paged=[0-9]+/, 'paged=' + pageNum);

这告诉它用给定的字符串替换&pageid=...(其中...是一系列一个或多个数字)。

于 2012-11-03T17:25:01.027 回答
1

You don't need to escape the =, and you have some additional slashes to match that don't exist in your sample url. Without them, it should work:

nextLink = nextLink.replace(/[?&]paged=[0-9]?/, 'paged='+ pageNum);
于 2012-11-03T17:23:38.703 回答
1

Yours:

nextLink = nextLink.replace(/\/paged\=\/[0-9]?/, 'paged='+ pageNum);

Mine:

nextLink = nextLink.replace(/&paged=[0-9]?/, 'paged='+ pageNum);

i.e. you wrote \/ when you meant &. You also wrote it before the digits for some reason. And you don't need to escape =.

于 2012-11-03T17:24:43.773 回答
1

既然可以使用优秀的URI.js,为什么还要使用正则表达式?

URI("myurl.com/?page_id=2&paged=2")
    .removeQuery("paged")  // remove so we don't have a duplicate
    .addQuery("paged", pageNum)
    .toString();

你不用担心逃跑,URI.js一切都为你做。

于 2012-11-03T17:33:41.680 回答
1

使用回调函数:

var r = new RegExp("paged=(\\d+)");
s = s.replace(r, function($1, $2){ return "paged=" + (parseInt($2, 10) + 1); });

请参阅此演示

于 2012-11-03T17:36:38.840 回答
0

Too many slashes. \/ will try to match a literal slash which is not there:

nextLink = nextLink.replace(/paged=[0-9]?/, 'paged='+ pageNum);

However, I think there should be better methods to parse and re-assemble URLs in Javascript.

于 2012-11-03T17:22:53.253 回答
0

这是一个不使用正则表达式的解决方案。

var url ="myurl.com/?page_id=2&paged=2" , pageNum=3;
url = url.split("paged=")[0]+"paged="+pageNum;

演示

于 2012-11-03T17:28:48.483 回答