Viktor
Viktor

Reputation: 237

Javascript replace() and regex

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

Answers (7)

Ωmega
Ωmega

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

phant0m
phant0m

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

Clyde Lobo
Clyde Lobo

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;

DEMO

Upvotes: 0

T.J. Crowder
T.J. Crowder

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

Lightness Races in Orbit
Lightness Races in Orbit

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

Bergi
Bergi

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

Martin Ender
Martin Ender

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

Related Questions