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.

7 Answers 7

2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

+1, I would add a note about what kind of chars needs to be escaped.
Both answers works like a charm, just missed out on the '&' in the second argument. Thanks!
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);

Comments

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 =.

Comments

1

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.

Comments

1

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.

Comments

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.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.