Reputation: 237
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.
Upvotes: 0
Views: 406
Reputation: 43673
Use callback function:
var r = new RegExp("paged=(\\d+)");
s = s.replace(r, function($1, $2){ return "paged=" + (parseInt($2, 10) + 1); });
See this demo.
Upvotes: 1
Reputation: 16905
Why use regular expressions, when you can use the excellent URI.js
library?
URI("myurl.com/?page_id=2&paged=2")
.removeQuery("paged") // remove so we don't have a duplicate
.addQuery("paged", pageNum)
.toString();
You don't need to worry about escaping, URI.js
does everything for you.
Upvotes: 1
Reputation: 9174
Here is a solution without using regex.
var url ="myurl.com/?page_id=2&paged=2" , pageNum=3;
url = url.split("paged=")[0]+"paged="+pageNum;
Upvotes: 0
Reputation: 1074335
You're telling it to match /paged
, but there's no /paged
in your string. Also, [0-9]?
probably isn't what you want for the digits. Try this:
nextLink.replace(/\&paged=[0-9]+/, 'paged=' + pageNum);
That tells it to replace &pageid=...
(where ...
is a series of one or more digits) with the given string.
Upvotes: 2
Reputation: 385174
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 =
.
Upvotes: 1
Reputation: 664548
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);
Upvotes: 1
Reputation: 44259
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.
Upvotes: 0