0

I have a string containing an URL, containing /p[num], for example www.test.com/list/p12 (p is the page number used for pagination).

This is my attempt to get the URL without the page number in javascript:

url = url.replace("\\/p\\d+", '');

However, it doesn't replace anything. What am I doing wrong here?

JSFIDDLE: https://jsfiddle.net/t9p95p87/

2
  • 3
    You seem to be using regex syntax in a string literal that is passed directly to .replace(). Instead use regex literal. url = url.replace(/\/p\d+/, '') Your way would work if you passed that string to the RegExp constructor. url = url.replace(new RegExp("\\/p\\d+"), ''); Commented Jan 8, 2017 at 23:27
  • 1
    If that URL is coming from window.location or an a.href, and if the part to remove will always be at the start, you could handle it without a regex by modifying the .pathname property and assigning it back to the same property. Commented Jan 8, 2017 at 23:30

1 Answer 1

3

If you use regexp literal syntax your code works fine:

url = url.replace(/\/p\d+/, '');

I think what was happening in your code is that the double backslash before the /p was ending up being interpreted as a desire to match a literal backslash.

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

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.