Home > Net >  How do I split a string between / and " " based on an outgoing link click, when there are
How do I split a string between / and " " based on an outgoing link click, when there are

Time:06-10

JS Beginner here. I need to return itemName from a URL string, however, there are colons in the URL itself. When I split using ("""), I get an error that this won't work.

I have gotten this far, but I don't know what to change in my function to get the desired result. See the examples below:

Below is the URL:

 "https://www.website.com/items/item-name-1" "?date_1=2022-10-05&date_2=2022-10-07&amount=2" 

Below you can see my code.

  
   if ({{Outgoing link}})
  var itemName= {{Click URL}};
      return itemName.split("/")[5].split(".")[0];
   
    
    console.log(extractSliceFromUrl(itemName))

   } 

This is my expected result:

 "item-name-1"

This is the actual result I get:

 "item-name-1" "?date_1=2022-10-05&date_2=2022-10-07&amount=2"
 

CodePudding user response:

Would the following work?

It extracts whatever's between the last / and the first " ".

const url = "\"https://www.website.com/items/item-name-1\" \"?date_1=2022-10-05&date_2=2022-10-07&amount=2\"";
console.log(url.substring(url.lastIndexOf('/')   1, url.indexOf('" "')));

CodePudding user response:

I'd split by ? first:

const theURL = "https://www.website.com/items/item-name-1" "?date_1=2022-10-05&date_2=2022-10-07&amount=2";

theURL.split("?")[0].split("/")[5].split(".")[0];

CodePudding user response:

With the secondary result, you could just remove the ending using:

'"item-name-1" "?date_1=2022-10-05&date_2=2022-10-07&amount=2"'.replace(/("[^"] ?")\ /, '$1')

Explanation of /("[^"] ?")\ / (RegExp)

  • (...) catch the pattern (becomes the $1)
  • [^"] everything not "
  • ? get the shortest result possible
  • \ escape ( is a special symbol, this will treat it as plain text)

CodePudding user response:

please is the working code.

let strUrl = "https://www.website.com/items/item-name-1" "?date_1=2022-10-05&date_2=2022-10-07&amount=2";
let urlArray = strUrl.split("/");
let itemName = urlArray[4].split("?")[0];
console.log(itemName); 
  • Related