John Deacon
John Deacon

Reputation: 181

Trim a current URL of extra characters?

I have a function which compares the current url against Urls in an array in order to determine if there's an exact match. The array contains product page Urls, and we want to trim the current url to only 'www' through the text after the first slash. (www.etsy.com/blankets for example, as opposed to www.etsy.com/blankets/redblanket). We also want to eliminate the 'http' part of the current Url to get rid of potential problems with an http not matching up with https. I line 3, I tried implementing a found solution which doesn't appear to be working. How can I modify this to work for this purpose?

export const getRecommendations = url =>

browser.storage.local.get("competitors").then(({ competitors }) => {
const trimmed = url.substring(url.lastIndexOf('/') + 1);  //How do I modify this to be correct?
  // check if the domain exists in the known list of domains
  if (!competitors.includes(trimmed)) { 
    return 
  }
});

Upvotes: 0

Views: 206

Answers (2)

StackSlave
StackSlave

Reputation: 10627

Here's the RegExp you probably want:

let url = 'https://www.example.com/wow/neat';
const trimmed = url.replace(/^.*\/\/|\/[^\/]+\/?$/g, '');
console.log(trimmed);

Upvotes: 1

user4723924
user4723924

Reputation: 36

Array split() makes things very easy...

var S = 'http://www.etsy.com/blankets/redblanket';

var A = S.split('/');

S = A[2] + '/' + A[3];

console.log(S)

The result in S is "www.etsy.com/blankets"

Upvotes: 2

Related Questions