-5

I have a few URL's like these

  • https://{Domain}/rent/abcdef/2019/Canada
  • https:/{Domain}/buy/Supported/2019/Gill-Avenue

I want to remove '2019'or any part which contain only numbers from these Url's so that the Url's look as below

  • https://{Domain}/rent/abcdef/Canada

  • https:/{Domain}/buy/Supported/Gill-Avenue

How can i achieve this using javascript

SitecoreNoob
  • 301
  • 1
  • 3
  • 12

3 Answers3

3

You can try this;

let str = "https://test.com/rent/abcdef/2019/Canada";
str.replace(/\/\d+/g, '');
gzen
  • 1,206
  • 1
  • 8
  • 6
1

You should try something like that: split on '/', filter with a /d regex and rejoin with '/'

I can't try right now sorry

window.location.href.split('/').filter(substr => !(/^\d+$/.match(substr))).join('/')
Alexandre Senges
  • 1,474
  • 1
  • 13
  • 22
  • 1
    You can simply use the `replace` function to solve this problem without having to call 4 separate functions. It would be faster, cleaner, and more simple to understand. – Grafluxe Aug 09 '19 at 13:51
  • "I can't try right now sorry" What do you mean by that? – new Q Open Wid Aug 09 '19 at 14:01
0

Try to do this for the first:

var str = "https://example.com/rent/abcdef/2019/Canada"
str = str.replace(/[0-9]/g, '');
str = str.replace("f//", "f/");

And for the second:

var str = "https://example.com/rent/abcdef/2019/Canada"
str = str.replace(/[0-9]/g, '');
str = str.replace("d//", "d/");

So this is if you want to replace just 1 digit. The first one of each of these works but adds a new / backslash to the whole link after the last letter before the / in the old version. To remove that, you do the second, which contains the last letter to not remove the :// too. The way is to find the last letter of each of these numbers before the backslash after using the first replace() function and replace them to remove the extra backslash.

This might work for easy things, like if you already know the URL, but for complicated things like a very big project, this is no easy way to do it. If you want "easy", then check other answers.

As said, you can also do this:

let str = "https://test.com/rent/abcdef/2019/Canada";
var withNoNum = str.replace(/\/\d+/g, '');

This is going to remove groups of numbers. So I added a new string withNoNum which is str's replacement with no numbers, which might be more good because if you are doing a website that allows you to send your own website and remove the numbers from it to get a new site.

This also might help you with this problem: removing numbers from string

new Q Open Wid
  • 2,225
  • 2
  • 18
  • 34